user2588317 user2588317 - 1 year ago 81
CSS Question

Variable image aspect ratios in a square box

I have a database for house listings with images of the homes for each entry. The images are uploaded by a 3rd party and they send images in random widths and lengths. Some are square-ish, some are portrait, some are landscape, etc. Without using javascript, what would be the best way to have the image completely fill a square div that is a definite size (200px by 200px, for example). I think using the image as a background image of each div and using "display: cover" would work great but not sure of any browser compatibility issues or maybe there is a better way. any suggestions?

Answer Source

If compatibility is what you care about, this is the best way to give everyone a decent experience:

div {
  background-position: 50% 50%;
  background-size: cover;
  width: 200px;
  height: 200px;
  overflow: hidden;
  position: relative;

img {
  position: absolute;
  max-width: 100%;
  max-height: 100%;
  left: calc(-2000px);
<div style="background-image: url(">
  <img src="" />

Basically, use background-size to scale where available, and show the image to all browsers that don't support calc. Two birds, one stone.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download