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?!?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With