将列与display:table对齐

时间:2014-01-21 09:00:47

标签: html css

我正在尝试使用HTML table属性呈现css布局:

display:table, table-row, table-cell...

这是我想要的:

+---------------+---------------------------------------+-----------------+
| my li         |            a content in a li          | another content |
+---------------+---------------------------------------+-----------------+
| my li         | a longer content that expend the cell | another content |
+---------------+---------------------------------------+-----------------+
| my li         |        foo bar foo bar in a li        |    a content    |
+---------------+---------------------------------------+-----------------+

这就是我得到的:

+---------------+-------------------+-----------------+
| my li         | a content in a li | another content |
+---------------+---------------------------------------+-----------------+
| my li         | a longer content that expend the cell | another content |
+---------------+---------------------------------------+-----------------+
| my li         | foo bar foo bar in a li |    a content in li    |
+---------------+-------------------------+-----------------------+

有没有办法对齐 而不明确设置width

以下是代码:

#container{
  display: table;
  border: 1px solid orange;
}
#container ul {
  display: table-row;
  border: 1px solid cyan;
}
#container ul li {
  display: table-cell;
  border: 1px solid magenta;
  vertical-align: middle;
  text-align: center;
}
#container ul li:first-child  {
  text-align: left;
}


<div id="container">
<ul><li>my li</li><li>a content in a li</li><li>another content</li></ul>
<ul><li>my li</li><li>a longer content that expend the cell</li><li>another content</li></ul>
<ul><li>my li</li><li>foo bar foo bar in a li</li><li>a content in li</li></ul>
</div>

2 个答案:

答案 0 :(得分:0)

table-layout: fixed;添加到#container选择器:

#container {
    display: table;
    table-layout: fixed;
    ...
}

来自MDN's notes on table-layout

  

表和列宽度由table和col元素的宽度或第一行单元格的宽度设置。后续行中的单元格不会影响列宽。

答案 1 :(得分:0)

好的,我检查了代码,如果我只有上面写的代码段,它也适用于我。 在我的应用中,由于为float:left声明了li{...},因此无法正确显示...我用

更正了
#container ul li{
... 
float: none;
}

感谢您的帮助。