Scale Up and Crop an Image WordPress [code snippet]

Download FREE Marketing Guides
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
I share digital marketing tips and HubSpot tutorials to help marketers and business owners grow their business.


Related posts

Tags: , ,

Want to Get Email Updates of New Articles?

Join My Email Newsletter