Home > Net >  In CSS, If the default behavior of position: absolute is display:block then why is my output showing
In CSS, If the default behavior of position: absolute is display:block then why is my output showing

Time:03-16

div
{
  width:200px;
  height:200px;
  position: absolute;
}

.first-container
{
  background-color: #9AD0EC;
}

.second-container
{
  background-color: red;
  left: 200px;
}

.third-container
{
  background-color: blue;
  left:400px;
}

Even if I override the display property to block, it still gives the same output. Why isn't the division element blocking the space ahead of it? Output : enter image description here

Rather than :

enter image description here

CodePudding user response:

An absolutely positioned element no longer exists in the normal document flow. Instead, it sits on its own layer separate from everything else. Rather than positioning the element based on its relative position within the normal document flow, they specify the distance the element should be from each of the containing element's sides. developer.mozilla.org/en-US/docs/Web/CSS/position (the "containing element" is the initial containing block.) top, bottom, left, and right use to position that relative to containing block.

explain reason with your code ---

/* when you give 'div' style like this nested div's also get position absolute*/
/* absolute positioned elements positions relative to its nearest positioned element.*/
/* then each container div's positioned relative to its nearest div */
/* comment this div style and use below div for solution. */
div { 
width: 200px;
height: 200px;
position: absolute;
}

/* positioned relative to upper div */
.first-container {
background-color: #9ad0ec;
}

/* positioned relative to nearest positioned (first-container) div */
.second-container {
background-color: red;
left: 200px;
}
/* positioned relative to nearest positioned (second-container) div */
.third-container {
background-color: blue;
left: 200px;
top: 200px;
}
<body>
<div>
  <div  />
  <div  />
  <div  />
</div>
</body>

need to set 'top' or 'bottom' to container-style to display required output. check this sandbox

  • Related