Scale Up and Crop an Image WordPress [code snippet]


Scale Up and Crop an Image WordPress [code snippet]

In WordPress you may need to increase the size of all thumbnails but WordPress does not res up the images to prevent distortion. Using the method outlined in this example you can use object-fit to make undersized images fit your desired aspect ratio. .img-crop__polyfill image is sized to the desired dimensions. This will help keep the aspect ratio the same for undersized images.

HTML

<div class="img-crop">
   <img src="https://dummyimage.com/1000x490/ccc/000" class="img-crop__objectfit" data-object-fit="cover">
   <img src="https://dummyimage.com/1640x690/000/fff" class="img-crop__polyfill"></div>
</div>

CSS

.instructions {
  background: #fff;
  padding: 2rem;
  margin-bottom: 1rem;
}

.img-crop {
  border: 1px solid #e2e2e2;
  position: relative;
  overflow: hidden;
}
.img-crop__polyfill {
  max-width: 100%;
  height: auto;
  opacity: 0;
}
.img-crop__objectfit {
  object-fit: cover;
  width: 100%;
  position: absolute;
  top: 0;
}

Resize your browser window to see how the undersized image fits the container.

See the Pen
Responsive Image Crop Using a Polyfill Image
by Jacob Lett (@JacobLett)
on CodePen.



Written by: Jake Lett
Jake Lett is a B2B marketing consultant with over 15 years of experience in the digital marketing industry. He specializes in SEO, HubSpot, and PPC campaign management. Jake has a proven track record of helping businesses increase their online visibility and drive more traffic, leads and sales. He is a Certified Google Ads Specialist and a Certified HubSpot Developer.

Topic:

Related posts

Tags: , ,

Want to Get Email Updates of New Articles?

Join My Email Newsletter