tags:

views:

222

answers:

5

I have a markup like this:

<div>
  <img />
</div>

The div is higher than img:

div {
  height: 100px;
}

img {
  height: dynamic-value-smaller-than-100px;
}

I need the image to be in the middle of the div (have same amout of white space above and below it).

I tried this and it does not work:

div {
  vertical-align: middle;
}
+6  A: 

if your image is purely decorative, then it might be a more semantic solution to use it as a background-image. You can then specify the position of the background

background-position: center center;

If it is not decorative and constitutes valuable information then the img tag is justified. What you need to do in such case is style the containing div with the following properties:

div{
    display: table-cell; vertical-align: middle 
}

Read more about this technique here. Reported to not work on IE6/7 (works on IE8).

pixeline
It is not decorative. I am building a list of company logos that work as a link actually, but nice idea anyway.
Josef Sábl
i've updated my answer accordingly.
pixeline
Great, it works! Please, just add info that this css has to be added to div, not img, it confused me a bit. Thanks a lot.
Josef Sábl
Mind that this won't work in IE6 and IE7 (not sure about IE8)
kemp
IE8 works well.
Josef Sábl
It works in IE8, but not IE6/IE7.
Shawn Steward
A: 

In your example, the div's height is static and the image's height is static. Give the image a margin-top value of ( div_height - image_height ) / 2

If the image is 50px, then

img {
    margin-top: 25px;
}
mwc
No, images height is dynamic.
Josef Sábl
A: 

Have you tried setting margin on the div? e.g.

div {
    padding: 25px, 0
}

for top and bottom. You may also be able to use a percentage:

div {
    padding: 25%, 0
}
Keith Bloom
this can't be used as I don't know the height of an image.
Josef Sábl
+1  A: 

I've posted about vertical alignment it in cross-browser way (http://stackoverflow.com/questions/2172789/vertically-center-multiple-boxes-with-css/2172842#2172842)

Create one-cell table. Only table has cross-browser vertical-align

Dewfy
+2  A: 

This is a solution I've used before to accomplish vertical centering in CSS. This works in all the modern browsers.

http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

Excerpt:

  <div style="display: table; height: 400px; #position: relative; overflow: hidden;">
    <div style=" #position: absolute; #top: 50%;display: table-cell; vertical-align: middle;">
      <div style=" #position: relative; #top: -50%">
        any text<br>
        any height<br>
        any content, for example generated from DB<br>
        everything is vertically centered
      </div>
    </div>
  </div>

(Inline styles for demonstration purposes)

Shawn Steward