skip to Main Content

When the div container that contains the paragraph elements is given relative positioning the background color covers all the paragraphs completely and it should because paragraphs are block elements, but if the position is set to absolute the background color kind of shrinks to only the paragraphs and not the length of the browser.

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

h1 {
  margin-bottom: 15px;
}

div#container {
  background-color: #00FFFF;
  position: relative;
  top: 50px;
}

p {
  width: 50px;
  height: 50px;
  border: 1px solid black;
  margin-bottom: 15px;
}

#p1 {
  background-color: #A52A2A;
  position: relative;
}

#p2 {
  background-color: #DEB887;
  position: relative;
  top: 65px;
  left: 65px;
}

#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>

Can you explain what is happening here?

2

Answers


  1. When the container div has position: relative, it is in the normal document flow and takes up the full width of its parent by default. Thus, the background color extends to the full width of the browser.

    When you set position: absolute, the container div is taken out of the normal flow and its width becomes only as wide as its content (stacked p elements). To maintain the full width of the browser for the background color, add width: 100% to the container div:

     
    
    * {
          box-sizing: border-box;
          margin: 0;
          padding: 0;
        }
        h1 {
          margin-bottom: 15px;
        }
    
        div#container {
            background-color: #00FFFF;
            position: absolute;
            top: 50px;
            width: 100%; /* Add this line */
        }
        p {
          width: 50px;
          height: 50px;
          border: 1px solid black;
          margin-bottom: 15px;
        }
        #p1 {
          background-color: #A52A2A;
          position : relative;
    
        }
        #p2 {
          background-color: #DEB887;
          position : absolute;
          top : 65px;
          left : 65px;
        }
        #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>

    Login or Signup to reply.
  2. because #p2 is a relative element, relative element it’s space is hold, and it’s position is relative.

    So the parent container just know relative element’s space postion, don’t know it’s actual position.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search