开发者

How to align text and image in a CSS box?

开发者 https://www.devze.com 2022-12-15 04:43 出处:网络
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\"

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://screencas开发者_JS百科t.com/t/Yzg2MzAzNW

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


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


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> 


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.


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> 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号