I have an outer <div>
that is relatively positioned and with a defined size. Inside it, I have a <table>
object that is absolutely positioned and with top
, left
, right
and bottom
set to zero. I expected the table to be expanded to obey the top/left/right/bottom constraints, however, this is not what happens. Instead, the table dimensions are calculated based on its contents.
If I use an inner <div>
instead of a <table>
, then it works as I expected. On the other hand, if I put display: table;
at the inner <div>
, then it behaves exactly like a table.
My question is: why does it happen? Where in the specifications is this behavior defined? Or is it a bug in browsers (very unlikely)?
I've checked the CSS 2.1 specification, I've read the sections 9.7 Relationships between 'display', 'position', and 'float', 10.3.7 Absolutely positioned, non-replaced elements, 17 Tables. I've also checked the position CSS attribute in Mozilla Developer Network. I've also searched in StackOverflow. And, still, I can't find an explanation on why tables behave like this.
See a live demo: http://jsfiddle.net/LgCDE/2/ I can reproduce the results on both Chrome 27 and Firefox 20.0.
HTML:
<div class="box">
<table class="table">
<tr>
<td>Hey!</td>
</tr>
</table>
</div>
<div class="box">
<div class="table">Hey!</div>
</div>
<div class="box">
<div class="table" style="display: table;">Hey!</div>
</div>
CSS:
div.box {
position:relative;
border: 2px dashed red;
background: #800;
width: 100px;
height: 50px;
}
.table {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: auto;
height: auto;
margin: 0;
border: 3px double blue;
background: #CCF;
table-layout: fixed;
border-collapse: collapse;
}
The answer, I believe, lies in the CSS2.1 specs, specifically Section 17.5.2: Table width algorithms: the 'table-layout' property (emphasis mine):
Note that this section overrides the rules that apply to calculating widths as described in section 10.3. In particular, if the margins of a table are set to '0' and the width to 'auto', the table will not automatically size to fill its containing block. However, once the calculated value of 'width' for the table is found (using the algorithms given below or, when appropriate, some other UA dependent algorithm) then the other parts of section 10.3 do apply. Therefore a table can be centered using left and right 'auto' margins, for instance.
As you noted, with width
set to auto
, the width will be based on the contents, rather than the containing block.
There's also this line at the end of that section, although I'm guessing it hasn't happened yet:
Future updates of CSS may introduce ways of making tables automatically fit their containing blocks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With