Home > Software design >  Why does a div with ::after selector position itself inside the original div in CSS
Why does a div with ::after selector position itself inside the original div in CSS

Time:11-09

Let's take the following example:

.box {
  display: flex;
  width: 200px;
  height: 250px;
  background: red;
}

.box::after {
  content: "";
  background: green;
  width: 200px;
  height: 250px;
}
<div ></div>

The problem I faced, is that the first div get positioned inside the second one as you can see in this image:
enter image description here

How can I fix this problem to have the original div (the red one) followed by the div with the ::after selector (the green div)

CodePudding user response:

You can set the parent div's position to relative, set the after pseudo element's position to absolute, and set it's left to 100% so that it'll start from the right side of it's parent container(red div)

.box {
  display: flex;
  width: 200px;
  height: 250px;
  background: red;
  position: relative;
}

.box::after {
  content: "";
  background: green;
  width: 200px;
  height: 250px;
  position: absolute;
  left: 100%;
}
<div >f</div>

  •  Tags:  
  • css
  • Related