views:

141

answers:

4

I would like to vertically align some text and an image in a CSS box.

I tried several methods, here is the code for the last one I tried called "display:table-cell-method"

<div style="border-color:blue; height:200px; display:table-cell; vertical-align:middle;">
2:38<img src="images/stopwatch-button-play.png">
</div> 

Here is a screenshot of the result in the newest version of Firefox: http://screencast.com/t/Yzg2MzAzNW

The image is centered correctly, the text is only centered nearly correctly. It sits at the baseline of the image. Why?

+4  A: 

vertical alignment is thoroughly misunderstood. Have you read this?

as for why the text sites at the baseline of the image, it is because the image and the text are both in the flow of the div. they will not overlap. to have the text centered too (implying it lies over the image), you will have to put the text into a div or a span and adjust its positioning (set it to relative and experiment with left and top).

Cheers

Here Be Wolves
As a matter of fact: Yes, I did read this, aprox. 90 minutes before I gave up searching the answer with google and posted on stackoverflow.
Sandra
A: 

You can use the background-position property.

it looks like this.

background: url(path/to/image.whatever) top; //aligns it to the top.

you can even do something like top left or top right etc.

w3schools has everything you need to know about backgrounds.

Derek Adair
+1  A: 

change the following

<div style="border-color:blue; height:200px; display:table-cell; vertical-align:middle;">
2:38<img style="vertical-align:middle" src="images/stopwatch-button-play.png">
</div> 
peacmaker
Thank you so much! That did it.
Sandra
welcome any time
peacmaker
A: 

Hi,

If your text is only one line high, you can set line-height to the height of your image. It will center the text vertically. Then position:absolute on your image will prevent it from disturbing the positioning of the text in the div:

<div style="border-color:blue; height:200px; ">
<div style="line-height:30px;margin-top:85px">2:38<img style="position:absolute" src="images/stopwatch-button-play.png"></div>
</div> 
Alsciende