Search code examples
htmlcsspositioncss-positionabsolute

What's the standard of width % for child positioned: absolute


As I know, child's width percentage's standard is parent's content box(only the content, without padding or margin.). So if there's a padding in parent and child's width is 100%, child's width is smaller than parents. But If I position child as a absolute and parent as a relative, child's width is just equal to the parent's no matter padding and margin in parents. Like this:

<div class="first">HI
<div class="second">
HELLO
</div>
</div>

css code

 .first{
 background-color: yellow;
 width:100px;
 height:100px;
 padding:10%;
 position:relative;

}
.second{
background-color: blue;
position:absolute;
width: 100%;
height:100%;
opacity:40%;
 }

Eventhough parent's position and relative so Child is totally dependent on '.first'. What's the standard of child's width in this case?


Solution

  • This snippet shows the result of setting the second div to have position relative and then position absolute. You can see that the absolutely positioned element takes on the width of its parent including the padding.

    enter image description here

    .first {
      background-color: yellow;
      width: 100px;
      height: 100px;
      padding: 10%;
      position: relative;
    }
    
    .second {
      background-color: blue;
      width: 100%;
      height: 100%;
      opacity: 40%;
    }
    
    .relative {
      position: relative;
    }
    
    .absolute {
      position: absolute;
    }
    <h2>The blue square has relative position</h2>
    <div class="first">HI
      <div class="second relative">
        HELLO
      </div>
    </div>
    <h2>The blue square has absolute position</h2>
    <div class="first">HI
      <div class="second absolute">
        HELLO
      </div>
    </div>

    The reason seems to be that:

    when a box has position: absolute its containing box is the parent's padding box.

    See the accepted answer to: Absolute positioning ignoring padding of parent though I am struggling to find the exact description of that in the actual standard documents and it would be good if someone could point out a primary reference.

    UPDATE: thanks to Temani Afif who has pointed out this SO answer which has info. from an actual specification: