showkey
showkey

Reputation: 318

Why child's width does not expand into parent's width in display: table-cell?

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>

Now the child element p here does not expand into its' parent's width and height: 100px, why? If the display: table-cell changed into display: table or others such as block, the child element <p> here does expand into its' parent's width and height :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>

Is there a rule to explain the action here?

Upvotes: 2

Views: 1650

Answers (2)

Sravan
Sravan

Reputation: 18657

The rule you asked,

If you declare display:table-cell then you have to nest it within elements with display:table-row and display:table. Just like a real table.

The link which says about that usage

Explanation of table cell:


table-cell: Let the element behave like a <td> element

Using height with table-cell columns:

Table-cell Columns expand to match the height of the largest column in the row. The height is defined by the content and not an explicit fixed height.

.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>

Column 1. Column 2 is a bit longer. Column 3 is longer with lots of text in it.

A common workaround for floated elements is to set a min-height value.

This works if the length of the longest content is always roughly the same, but isn’t a viable solution if the length of the content varies significantly.

Here is a reference to this answer


Applying the rule to your 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

Upvotes: 1

BoltClock
BoltClock

Reputation: 724452

The p with display: table-cell is rendered in an anonymous table-row box, in an anonymous table box (§17.2.1 Anonymous table objects), within the div (which then becomes this anonymous table box's containing block).

A table box doesn't expand to the width of its containing block by default (§17.5.2 Table width algorithms: the 'table-layout' property). This is true of anonymous table boxes, HTML table elements, and any other element with display: table.

Upvotes: 2

Related Questions