Satch3000 Satch3000 - 5 months ago 27
CSS Question

CSS responsive image not staying square

I have an image where the src is loaded dynamically so I don't know the size of it and I also need to keep it responsive so I've set:

.resImg {
display:block;
border:5px solid yellow;
width:100%;
overflow: hidden;
}


The problem is that I need to maintain the image squared while still in percentages but some images are appearing rectangular.

How can I do this?

Answer

Here's a neat CSS trick:

.resImg {
  display:block;
  border:5px solid yellow;
  width:100%;
  overflow: hidden;
  padding-bottom:100%;
  background:url(http://lorempizza.com/500/500) scroll no-repeat center/cover;
}
<div class="resImg"></div>

How does it work?

If the padding is set to a percentage, that percentage is calculated from the width of the element. If you want to make the element as tall as it is wide, set the padding-bottom(or padding-top) to 100%, and the height will be 100% of the width.

To address the issue with different sized images, just set the image as a background image, like I did in my example.

Here's a JSFiddle to play with

Comments