垂直对齐中间显示表格单元格不工作的图像 [英] Vertical-align middle with display table-cell not working on images

查看:120
本文介绍了垂直对齐中间显示表格单元格不工作的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用vertical-align:middle在布局上垂直居中有时文本,有时图像,但它只工作在文本。任何人都可以告诉我为什么?



HTML:

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

< div>
< span>文字< / span>
< / div>

CSS:

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

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

http://jsfiddle.net/9uD8M/ 我创建了一个小提琴

解决方案

放置<$ c $在 img,span 标签上的c:border:1px solid black ,然后在浏览器开发环境中检查这两个元素。安慰。您会注意到,span默认为其父级的100%高度,而图像具有定义的高度(实际图像的高度)。



所以你不是真的垂直对齐这些元素相对于div,你只是垂直对齐的span元素内的文本相对于span:)

如果你真的想使用表来进行垂直定心,这里是正确的代码:
http://jsfiddle.net/WXLsY/



vertical-align display:table-cell 去父母,你需要包装表)



但是还有其他方法做这个(SO有这个问题的很多答案,只是使用搜索)


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

解决方案

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)

这篇关于垂直对齐中间显示表格单元格不工作的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆