Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vertically center image within responsive square div

I am trying to center an image inside a div that scales responsively and that is always square.

JSFiddle

I've got the always-square part working thanks to the awesome CSS-only option here.

CSS:

.thumbnail_container {
    position: relative;
    width: 25%;
    padding-bottom: 25%;
    float:left;
}

.thumbnail {
    position:absolute;
    width:100%;
    height:100%;
    text-align:center;
}

HTML:

<div class="thumbnail_container vcenter-ext">
  <div class="thumbnail vcenter-int">
      <img src="http://placehold.it/200x300" />
  </div>
</div>

And the v-align in a div is usually pretty straight-forward with:

.vcenter-ext { display: table;}
.center-int { display: table-cell; vertical-align: middle;}

But in the end, I can't seem to use them together... Can anyone point out my problems?!?

like image 790
Shawn Taylor Avatar asked Jul 30 '26 12:07

Shawn Taylor


1 Answers

To solve your problem, you have to remove display: table; and display: table-cell; vertical-align: middle; and have to add this :

.thumbnail img {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}

to center vertically your images. This article explains the method I used (Absolute Positioning and Stretching).

Note : my code is working because .thumbnail, the parent of img tags, has a position: absolute property.

You can have a look to this fiddle to see the result.

like image 145
Lucas Willems Avatar answered Aug 01 '26 07:08

Lucas Willems