Dexter Adams
Dexter Adams

Reputation: 524

How do you center image inside square aspect ratio and maintain responsiveness?

I'm creating a product grid for a client and was faced with the issue of properly centering a dynamic thumbnail (sometimes square, portrait, or landscape) in a square aspect ratio and maintaining responsiveness.

I am currently doing the following but was wondering if there was a more clean css solution for centering an image (vertically/horizontally) inside of a div much like you would with a background image on a responsive div with background-size: contain.

.thumbnails {
  margin: auto;
  width: 250px;
}

.thumbnail {
  position: relative;
  margin: 1rem;
  padding-bottom: 100% ;
  border: 1px solid gray;
}

.thumbnail__img {
  position: absolute;
  max-width: 100% ;
  max-height: 100% ;
  width: auto;
  height: auto;
  left: 50% ;
  top: 50% ;
  transform: translate(-50% , -50% );
}
<div class="thumbnails">
  <figure class="thumbnail">
    <img class="thumbnail__img" src="https://dummyimage.com/300x600/000/fff">
  </figure>

  <figure class="thumbnail">
    <img class="thumbnail__img" src="https://dummyimage.com/600x300/000/fff">
  </figure>

  <figure class="thumbnail">
    <img class="thumbnail__img" src="https://dummyimage.com/600x600/000/fff">
  </figure>
</div>

Demo JSFiddle

Upvotes: 0

Views: 3881

Answers (1)

joohong89
joohong89

Reputation: 1271

Here's an alternative using object-fit: contain;.

This way there is no need to use transform and meddle with left/top.

.thumbnails{
  width: 250px;
}

.thumbnail{
  position: relative;
  margin: 1rem;
  padding-bottom: 100%;
  border: 1px solid gray;
}

.thumbnail__img{
  position: absolute;
  width: 100%;
  height: 100%;
  object-fit: contain;
  display: block; // important since images have default inline-block property
}
<div class="thumbnails">
  <figure class="thumbnail">
    <img class="thumbnail__img" src="https://dummyimage.com/300x600/000/fff">
  </figure>

  <figure class="thumbnail">
    <img class="thumbnail__img" src="https://dummyimage.com/600x300/000/fff">
  </figure>

  <figure class="thumbnail">
    <img class="thumbnail__img" src="https://dummyimage.com/600x600/000/fff">
  </figure>
</div>

Upvotes: 2

Related Questions