Vertical-align middle with display table-cell not working on images

旧街凉风 提交于 2019-12-08 14:47:03

问题


I'm trying to use the vertical-align: middle on a layout to vertically center sometimes text, sometimes images, but it's only working on text. Can anyone tell me why?

HTML:

<div>
    <img src="http://jsfiddle.net/img/logo.png"/>
</div>

<div>
    <span> text </span>
</div>

CSS:

div{
    width:200px;
    height:200px;
    background-color:red;
    display:table;

    margin:10px;
}
img, span{
    display:table-cell;
    vertical-align:middle;
}

http://jsfiddle.net/9uD8M/ I created a fiddle aswell


回答1:


Put border: 1px solid black on your img, span tags, then inspect both elements in the browser dev. console. You'll notice that the span defaults to 100% height of its parent, while the image has a defined height (the height of the actual image).

So you're not really vertically aligning those elements relative to the div, you're just vertically aligning the text inside the span element relative to the span :)

If you really want to use tables for vertical-centering, here's the correct code: http://jsfiddle.net/WXLsY/

(vertical-align and display:table-cell go on the parent, and you need wrapper table on them)

But there are other ways to do this (SO has many answers to this question, just use search)




回答2:


Here is one way of fixing the problem:

HTML:

<div>
    <span><img src="http://jsfiddle.net/img/logo.png" /></span>
</div>
<div> 
    <span> text </span>
</div>

Put your img in a span, the image is a replaced element, it cannot contain children content, hence, vertical-align will not work.

CSS:

div {
    width:200px;
    height:200px;
    background-color:red;
    display:table;
    margin:10px;
}
span {
    display:table-cell;
    vertical-align:middle;
}

See demo at: http://jsfiddle.net/audetwebdesign/Fz6Nj/

There are several ways of doing this, you could also apply display: table-cell to the parent div element, but that would be a different approach.




回答3:


In order to vertically align an image inside a table cell you need to give the image a display of block.

display: block
margin: 0 auto

the margin: 0 auto is to align the image to the center. If you want the image left aligned then don't include this. If you want the image right aligned you can add:

float: right

Thanks, G




回答4:


You can try by adding -> line-height: 200px; in the span style section, I think it might work;



来源:https://stackoverflow.com/questions/20584777/vertical-align-middle-with-display-table-cell-not-working-on-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!