基于绝对定位的父元素在子元素上设置"高度"

tre*_*der 1 css

我有一个父元素,我想在父元素中设置元素的高度.例如:

<div id="parent">
    <p id="child"></p>
</div>
Run Code Online (Sandbox Code Playgroud)

现在我们知道,为了设置"子"的高度,我们必须在"父"上设置一些高度值.否则,仅在"孩子"上设置任何高度值都没有效果.

#parent { height: 200px; }
#child { height: 75%; }
Run Code Online (Sandbox Code Playgroud)

这会将"child"的高度设置为200px的75%.如果我们删除"父"的高度,"child"将不会设置任何高度.

现在,我发现不是设置高度,如果我们将"父"的定位设置为绝对,我们可以在不设置任何高度的情况下离开,并且"子"上的高度值仍然有效:

#parent { position: absolute; top: 0; bottom: 0; }
#child { height: 75%; }
Run Code Online (Sandbox Code Playgroud)

我想知道的是这是一种标准行为还是偶然发生的事情.另外,如果它是标准的,这是否意味着给元素一个布局(通过设置它的位置)会给它一些隐含的高度值?

Bol*_*ock 5

The basic idea is this: for an absolutely-positioned element, if you set the offsets on opposite sides (e.g. left and right, or top and bottom) to zero, then the element will stretch to the width or height of its containing block respectively.

Not only is this a commonly-used trick, but it is also a standard behavior. The gory details are here in the spec; the key lies in this equation:

For absolutely positioned elements, the used values of the vertical dimensions must satisfy this constraint:

'top' + 'margin-top' + 'border-top-width' + 'padding-top' + 'height' + 'padding-bottom' + 'border-bottom-width' + 'margin-bottom' + 'bottom' = height of containing block

(This is for calculating heights; there's a corresponding equation for calculating widths as well, which can be found here.)

So, assuming defaults for all other values, this means

0 + 0 + 0 + 0 + 'height' + 0 + 0 + 0 + 0 = height of containing block

The containing block of an absolutely-positioned element whose ancestors are all static is always the viewport (or the initial containing block), which is typically of the same height as a browser's viewing area (or the Results iframe in jsFiddle for example). This creates the effect I've just described.

Because you did not specify an explicit height for your parent element, this gives it an implicit height for calculating the height of your child element as a percentage:

The percentage is calculated with respect to the height of the generated box's containing block.

In fact, even if you set top and/or bottom to some non-zero value, the boxes will scale according to the above equation.

Note also that the "height of the generated box's containing block" does not refer to the specified or computed value of height for that block, but the used value, i.e. the height as it is calculated rendered on screen. This may have been the source of your confusion on why you can get away without setting height on the parent element, yet the browser still knows how to calculate the height of the child element based on some implicit height.