为什么孩子的宽度不会扩展到父显示中的父宽度:table-cell?

时间:2016-11-09 13:48:51

标签: css css-tables

div {
  width: 100px;
  height: 100px;
}
p {
  margin: 0px;
  padding: 0px;
  display: table-cell;
  width: 100%;
  height: 100%;
  border: 1px solid green;
}
<div>
   <p>hello</p>
 </div>

现在这里的子元素p没有扩展到它的'父宽度和height: 100px,为什么? 如果display: table-cell已更改为display: table或其他内容,例如block, 此处的子元素<p>会扩展为其“父级widthheight :100px

div {
  width: 100px;
  height: 100px;
}
p {
  margin: 0px;
  padding: 0px;
  display: table;
  width: 100%;
  height: 100%;
  border: 1px solid green;
}
<div>
   <p>hello</p>
 </div>

这里有解释行动的规则吗?

2 个答案:

答案 0 :(得分:2)

pdisplay: table-cell呈现在匿名表格行框中,在匿名表格框中§17.2.1 Anonymous table objects), {{1}内然后变成这个包含块的匿名表格框。

默认情况下,表格框不会扩展到其包含块的宽度(§17.5.2 Table width algorithms: the 'table-layout' property)。对于匿名表格框,HTML div元素以及table的任何其他元素都是如此。

答案 1 :(得分:0)

你问的规则,

如果声明display:table-cell,则必须将其嵌套在具有display:table-row和display:table的元素中。就像真正的桌子一样。

The link which says about that usage

表格单元格的说明:

table-cell: 让元素表现得像<td>元素

将高度与表格单元格列一起使用:

表格单元格列展开以匹配行中最大列的高度。高度由内容定义,而不是明确的固定高度。

.container {
  display: table;
  height: 500px;
}

.column {
  display: table-cell;
  width: 100px;
}
<div class="container">
    <div class="column">Column 1.</div>
    <div class="column">Column 2 is a bit longer.</div>
    <div class="column">Column 3 is longer with lots of text in it.</div>
</div>

列1.第2列有点长。第3列较长,其中包含大量文字。

浮动元素的常见解决方法是设置最小高度值。

如果最长内容的长度总是大致相同,则可行,但如果内容的长度变化很大,则不可行。

Here is a reference to this answer

将规则应用于您的答案:

div {
  width: 100px;
  height: 100px;
  display: table;
}
p {
  margin: 0px;
  padding: 0px;
  display: table-cell;
  width: 100%;
  height: 100%;
  border: 1px solid green;
}
<div>
   <p>Test</p>
</div>

Here is a fiddle