做垂直居中,居中元素大小不固定,于是选择CSS table
的方式来解决,HTML结构如下:
<div id="parent">
<img src="pic64.png" class="box" />
<span class="box">Many text here.</span>
</div>
样式:
#parent {
height: 350px;
width: 600px;
background: yellow;
display: table;
}
.box {
display: table-cell;
vertical-align: middle;
}
结果是图片并没有垂直居中的效果,需要在img外套一个div才能达到预期效果,可行的HTML结构:
<div id="parent">
<div class="box">
<img src="pic64.png"/>
</div>
<span class="box">Many text here.</span>
</div>
为什么要额外套一个div呢?
你没搞清楚dom节点的结构
你开始的例子里面把
img
和span
同时加上box
类,然后给box类加上display: table-cell
,这里的img元素实际上本身就是你的内容元素,而span是一个容器,它下面还有一个文档节点
Many text here.
这个文档节点才是你的内容节点,table-cell在表格中也是一个容器元素,vtm将它的内容垂直对齐,你的img元素是个自闭合标签,它并没有内容,它自己就更不是它自己的内容了
之后套上个div就合乎情理了,在这里img元素实际上是和那个TextNode
Many text here.
等价的。说得比较绕不知道题主能不能明白?