-1

My question is so simple but rather problematic for me, if a parent div have padding and child's div width is 100%, child's div width is always shorter than its parent one. if i change child div as absolute div and parent div as relative, child's width is just equal to the parent's no matter padding and margin in parents. Like this:

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

.second {
  background-color: blue;
  position: absolute;
  width: 100%;
  height: 100%;
  opacity: 40%;
}
<div class="first">HI
  <div class="second">
    HELLO
  </div>
</div>

Eventhough parent's position is totally relative, so you assume Child is totally dependent on '.first'div. So, I am assuming how is child width is calculated in this case?

strek
  • 1,190
  • 1
  • 9
  • 19

1 Answers1

1

When you set child div to position absolute (and parent has position relative value), then this element is removed from the normal document flow. Also, if left property is set other than 'auto' it is normal to "ignore" the padding because according to W3C docs "These properties specify offsets with respect to the box's containing block" (if it's auto then it shouldn't ignore padding, but width: 100% will "ignore" padding and when parent has 100px then child also will have 100% width.). See also this for answer what is a containing block - https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block.

Izabela Furdzik
  • 511
  • 6
  • 8