0

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?

YESSS
  • 31
  • 4

2 Answers2

1

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:

A Haworth
  • 30,908
  • 4
  • 11
  • 14
0

The standard of the % for position:absolute is of the nearest positioned ancestor block and if no ancestor is positioned, it is relative to body element. In your case since the first is positioned relative the second will be relative to first and if u remove the position attribute of first, second will be positioned relative to body.

You can also check this - https://www.w3schools.com/css/css_positioning.asp