-1

I have a parent named "container" of size 300px x 120px that encapsulates 2 s namely "redbox" and "greenbox". when I add "position: relative" to the "container" size of child <div>s looks proportionate. however on removing the attribute size of div increases 3 times". to my knowledge position is for positioning of elements how can it effect the size of the element.

#container {
  width: 300px;
  height: 120px;
  /*position: relative;*/
  border: solid 1px blue;
}

#redbox,
#greenbox {
  border: solid 1px;
  width: 60%;
  height: 60%;
  position: absolute;
}

#redbox {
  background-color: red;
  left: 0px;
  top: 0px;
}

#greenbox {
  background-color: rgb(21, 255, 0);
  left: 30px;
  top: 30px;
  opacity: 50%;
}
<head></head>
<body>
  <div id="container">
    <div id="redbox"></div>
    <div id="greenbox"></div>
  </div>
</body>
Ritu
  • 714
  • 6
  • 14
  • it's all about containing block : *If the element has 'position: absolute', the containing block is established by the nearest ancestor with a 'position' of 'absolute', 'relative' or 'fixed', in the following way:* – Temani Afif Aug 17 '20 at 14:54

1 Answers1

2

The reason this is happening is because you are using percentages for your width and height. Absolute positioning is relative to the nearest parent that has position: relative If nothing qualifies for that, the parent is the <body> element.

When you set position: relative on the #container, you are changing the size of the relative parent to the red and green boxes. And since you are using percentages, the size of the red and green boxes change accordingly.

Dan Mullin
  • 4,285
  • 2
  • 18
  • 34