2

I'm trying to vertical align my ing element within a div. Only problem is the img element doesn't have a fixed height. I tried vertical-align in combination with table, table-cell and inline-block and inline. None of this seems to work. Does anyone have any idea how I can achieve this? I made a JSFiddle that recreates my problem.

JsFiddle: http://jsfiddle.net/6gMcK/1/

HTML:

<div id="image-container">
    <img src="http://www.image2012.com/images/2013/03/landscapes-landscape-free.jpg">
</div>

CSS:

#image-container {
    padding:5px;
    height: 135px;
    border: 1px solid black;
    display: table;
    float:left;
}

#image-container img{
    display: table-cell;
    max-height:125px;

    vertical-align: middle;
}
Frank Kluytmans
  • 533
  • 2
  • 10
  • 25

3 Answers3

1

Change some properties as like this

   #image-container {
    padding: 5px;
    height: 135px;
    border: 1px solid black;
    display: table-cell;
    vertical-align: middle;
}

#image-container img{
    max-height: 125px;
    display: block;
}

Live Demo

skobaljic
  • 9,379
  • 1
  • 25
  • 51
Rohit Azad Malik
  • 31,410
  • 17
  • 69
  • 97
0

A solution I often use is to have the image be the background of the image container. This way I can set the width and height to whatever it needs to be and for any image and size of the container, with a little absolute positioning and the full image is always displayed.

#image-container {
    position:absolute;
    left:30%;
    right:30%;
    min-width:135px;
    height: 135px;

    border: 1px solid black;
    background-image:url('image.png');
    background-size:contain;
    background-repeat:no-repeat;
    background-position:center;
}

Of course you can always play around with the values for the width depending on what your needs are. I always found this to be a simple solution for displaying images.

Matt Kelliher
  • 99
  • 1
  • 1
  • Please note: These are CSS3 properties, so this solution will work on modern browsers, but not on IE<9. – skobaljic Apr 24 '13 at 12:13
0

If you just have one image in the container , and the container has a fixed height, then you could simply apply line-height = container_height_px to the container

Try this demo

Danield
  • 121,619
  • 37
  • 226
  • 255
  • If we reduce the img-container height to 100px, we can see the image is not exactly vertically centered (which may be annoying in some cases), cause it still has default display: inline. Best cross-browser solution for vertical centering is to use old table and give the img display: block. It would work on 20th century browsers too. – skobaljic Apr 24 '13 at 12:10
  • The question didn't say that the container had a variable height, it said the the **img** had a variable height – Danield Apr 24 '13 at 12:21