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.


About the Author

Jacob Lett is the founder of Bootstrap Creative, a digital marketing consultancy that helps Michigan manufacturers generate qualified leads through HubSpot, technical SEO, and Google Ads. With over a decade of hands-on experience, he acts as a direct partner for B2B companies seeking measurable ROI from their marketing investment.



Related posts

Tags: , ,

| Read My Editorial Policy

Want to Get Email Updates of New Articles?

Join My Email Newsletter