avistein
avistein

Reputation: 102

How the absolute positioning works here?

If the absolute positioning removes the object from regular content flow, then why the div#container is still following those boxes (when the boxes' widths are reduced or increased, the div#container is too adjusting itself according to that and covering all the boxes. For example, when I set one of the box's positioning to absolute then the container too reduces itself)? And also why the container is just following the boxes, instead of the whole width (since div is a block level element)?

Screenshot

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
body {
  position: relative;
}
h1 {
  margin-bottom: 15px;
}
div#container {
  background-color: #00FFFF;
  position: absolute;
}
p {
  width: 50px;
  height: 50px;
  border: 1px solid black;
  margin-bottom: 15px;
}
#p1 {
  background-color: #A52A2A;
}
#p2 {
  background-color: #DEB887;
}
#p3 {
  background-color: #5F9EA0;
}
#p4 {
  background-color: #FF7F50;
}
  <h1>Positioning Elements</h1>

  <div id="container">
    <p id="p1"></p>
    <p id="p2"></p>
    <p id="p3"></p>
    <p id="p4"></p>
  </div>

Upvotes: 1

Views: 61

Answers (2)

Asaf David
Asaf David

Reputation: 3297

When an element has position absolute it means that it position is relative to it's first positioned parent, meaning it's first parent with position relative / absolute / fixed / sticky.

It still behaves the same according to it's children elements.

Upvotes: 1

Uzbekjon
Uzbekjon

Reputation: 11813

And also why the container is just following the boxes, instead of the whole width (since div is a block level element)?

That's because you set its positioning to absolute, thus forcing it to only take up space that is required by its children.

div#container { position: absolute; }

If you want to make it take up all the width, remove absolute positioning.


If the absolute positioning removes the object from regular content flow, then why the div#container is still following those boxes (when the boxes' widths are reduced or increased, the div#container is too adjusting itself according to that and covering all the boxes.

Add absolute positioning to your boxes and the parent container will no longer "follow" them.

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
body {
  position: relative;
}
h1 {
  margin-bottom: 15px;
}
div#container {
  background-color: #00FFFF;
  position: relative;             // < === HERE ===
}
p {
  width: 50px;
  height: 50px;
  border: 1px solid black;
  margin-bottom: 15px;
}
#p1 {
  background-color: #A52A2A;
}
#p2 {
  background-color: #DEB887;
}
#p3 {
  background-color: #5F9EA0;
}
#p4 {
  background-color: #FF7F50;
  position: absolute;             // < === HERE ===
}
  <h1>Positioning Elements</h1>

  <div id="container">
    <p id="p1"></p>
    <p id="p2"></p>
    <p id="p3"></p>
    <p id="p4"></p>
  </div>

Upvotes: 2

Related Questions