为什么“display:table-cell”弄乱了我的div?

时间:2012-11-06 04:30:45

标签: html css

我正试图将字符串“1”,“2”和“3”垂直居中,如下所示:

但是当我对所有3个div使用display: table-cell; vertical-align: middle;时,我得到了他不想要的结果:

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;
}

Demo

如何保持3 div垂直对齐,同时保持每个div内的垂直对齐?

4 个答案:

答案 0 :(得分:4)

这是一个概念上的误解。如果父元素没有display:table-row,则表格单元格将始终跨越整个宽度,因为它将创建table-rowtable的匿名表对象。

根据W3C规范文章: Tables

  

HTML以外的文档语言可能不包含CSS 2.1表模型中的所有元素。在这些情况下,必须假定“缺少”元素才能使表模型起作用。任何表元素都会自动生成必要的匿名表对象,包含至少三个对应于'table'/'inline-table'元素的嵌套对象,一个'table-row'元素,以及'table-cell'元素。 .....

Here是一个显示display: table等用途的quirksmode页面。图像显示与此问题相同的效果。

要在语义上解决此问题,您必须添加一个额外的元素以显示为行。

<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;
}

Demo

答案 1 :(得分:2)

我认为使用line-height

是一种更简单的方法
<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>

.each_div { 
     width: 80px;
     height: 50px; 
     line-height:50px;     // set to the same height as the div
     text-align: center;
     clear:both;}          // add clear both to skip line

请在此处查看jsfiddle并与其他答案进行比较。

enter image description here

答案 2 :(得分:1)

您可以使用<div>将每个display: table-row;包裹在另一个<div id='alldivs'> <div class="row"> <div id='red' class='each_div'>1</div> </div> <div class="row"> <div id='blue' class='each_div'>2</div> </div> <div class="row"> <div id='green' class='each_div'>3</div> </div> </div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ 中,它将按您的意愿显示:

HTML:

.each_div { 
     width: 80px;
     height: 50px; 
     display: table-cell; 
     vertical-align: middle;
     border: 1px #000 solid;
}
.row {
    display: table-row;
}​

CSS:

table-*

这是因为{{1}}旨在模拟表,因此必须遵循表结构才能获得表外观。在这种情况下,您可能只想使用表格。

答案 3 :(得分:0)

我找到了一种以你想要的方式工作的解决方法。如果您愿意,那么您可以使用它:

将您的CSS更改为:

.each_div { 
     width: 100%;
     height: 50px; 
     vertical-align: middle;
     text-align:center;
     background:red;

}
#alldivs{
    width:80px;
    display:block;
}

请注意,我已为父div width:80px

提及alldivs

它将输出显示为:

Output of above CSS

相关问题