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 results-driven B2B marketing consultant with 15+ years of experience helping businesses boost online visibility, generate qualified leads, and increase sales. Specializing in SEO, HubSpot, and PPC campaign management, Jake leverages proven strategies to deliver measurable growth. As a Certified Google Ads Specialist and HubSpot Developer, he is committed to driving impactful results for his clients.

Related posts

Tags: , ,

Want to Get Email Updates of New Articles?

Join My Email Newsletter