- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我试图将字符串“1”、“2”和“3”垂直居中,如下所示:
但是当我使用 display: table-cell; vertical-align: middle;
对于所有 3 个 div,但随后我得到了他不需要的结果:
HTML 是
<div id='alldivs'>
<div id='red' class='each_div'>1</div>
<div id='blue' class='each_div'>2</div>
<div id='green' class='each_div'>3</div>
</div>
CSS 是
.each_div {
width: 80px;
height: 50px;
text-align: center;
display: table-cell; vertical-align: middle;
}
如何保持 3 个 div 垂直对齐,同时在每个 div 内保持垂直对齐?
最佳答案
这是概念上的误解。如果没有带有 display:table-row
的父元素,表格单元格将始终跨越整个宽度,因为它将创建 table-row
和 table 的匿名表格对象
。
根据 W3C 规范文章: Tables
Document languages other than HTML may not contain all the elements in the CSS 2.1 table model. In these cases, the "missing" elements must be assumed in order for the table model to work. Any table element will automatically generate necessary anonymous table objects around itself, consisting of at least three nested objects corresponding to a 'table'/'inline-table' element, a 'table-row' element, and a 'table-cell' element. .....
Here是一个 quirksmode 页面,显示了 display: table
等的使用。显示与此问题相同效果的图像。
要从语义上解决这个问题,您必须添加一个额外的元素以显示为行。
<div id='alldivs'>
<div id='red' class='each_div'>
<div class="cell">1</div>
</div>
<div id='blue' class='each_div'>
<div class="cell">2</div>
</div>
<div id='green' class='each_div'>
<div class="cell">3</div>
</div>
</div>
然后给它们分配相对的CSS
#alldivs { display: table; }
.each_div {
display: table-row;
}
.cell {
width: 80px;
height: 50px;
display: table-cell;
vertical-align: middle;
border: 1px #000 solid;
}
关于html - 为什么 "display: table-cell"弄乱了我的 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13244412/
我是一名优秀的程序员,十分优秀!