0

I'm trying to vertically center an image inside a div that is floated left, and that has a min-height of 150px;

Problem is, nothing I try works. I tried everything from using display:table for the other div and using display:table-cell for the inner one, but everything stays the same.

The images that appear inside the div don't have a fixed height, but will be cut down to 150px on the server.

How can I get this to work?

![<!DOCTYPE HTML>
<html>
 <head>
  <title>The annoying image</title>
 </head>
<body>

<div style="border:1px solid #ddd; float:left; height:150px; padding:10px; display: table;">
    <img src="/imgur/us/thumb_1.jpg" style="display: table-cell; vertical-align: middle; text-align: center;">
</div>

</body>
</html>

enter image description here

enter image description here

A fiddle

Norman
  • 6,159
  • 23
  • 88
  • 141

1 Answers1

0

Here's the fiddle : http://jsfiddle.net/Cq48L/

html

<div class="outer">
    <span class="helper"></span>
    <img src="https://i.stack.imgur.com/e0Snp.jpg">
</div>

css

.outer {
    border:1px solid #ddd; 
    float:left; 
    height:150px; 
    padding:10px; 
    display: table;
}

.outer img {
     vertical-align: middle;
}
.helper {
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}

Check these answers as well : https://stackoverflow.com/a/18516474/3603806 and https://stackoverflow.com/a/7310398/3603806

Community
  • 1
  • 1
Himanshu Tyagi
  • 5,201
  • 1
  • 23
  • 43
  • 1
    Nice answer, but you can get rid of the helper element, like this: http://jsfiddle.net/Cq48L/4/ http://stackoverflow.com/questions/18516317/vertically-align-an-image-inside-a-div-with-responsive-height + there is no need for the `display: table;` – Nico O Jul 19 '14 at 15:08
  • @NicoO Nice approach, but fails in IE (I'm using IE9). – Norman Jul 19 '14 at 15:14
  • @Norman You have seen the old version of the comment. I did not see there was a sensless `display: table`. I allready removed that, check again. Works with firefox and even IE8 – Nico O Jul 19 '14 at 15:19
  • @NicoO I checked you answer. Funny thing is, it displays correctly in the fiddle, but on my test machine (Win 7 64 and all browsers) the image has extra space on the left than the right. I spent all this time trying to fix that. What an I doing wrong? I'm using your code with no changes. – Norman Jul 19 '14 at 15:53
  • @NicoO Please check the new image I uploaded. – Norman Jul 19 '14 at 15:54
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/57608/discussion-between-norman-and-nico-o). – Norman Jul 19 '14 at 16:12