3

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?!?

Community
  • 1
  • 1
Shawn Taylor
  • 15,590
  • 4
  • 32
  • 39
  • if you dont care about [= – Rick Lancee May 20 '14 at 06:25
  • You could take a look at this answer , responsive squares with content : http://stackoverflow.com/a/20457076/1811992 it describes a good technique to center content inside responsive squares. – web-tiki May 20 '14 at 11:26

2 Answers2

8

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.

Lucas Willems
  • 6,673
  • 4
  • 28
  • 45
0

Something like this?

HTML:

<div>
<img src="http://placehold.it/200x300" /> 

Css:

body{margin:0px auto;padding:0;text-align:center;}
div{padding:80px;width:25%;margin:0px auto;background:green;}
img{width:80%;margin:0px auto;padding:0;}

http://jsfiddle.net/8Fjsd/

Also:

vcenter-int doesnt exist

ImAtWar
  • 1,073
  • 3
  • 11
  • 23