Confused by ::before and ::after

Hello,

I’m confused by the “Applied Visual Design: Create a More Complex Shape Using CSS and HTML” lesson - I thought the ::before and ::after pseudo-elements added content before and after the selected element, respectively.

But when I change the color and default the position of the ::before and ::after pseudo-elements (to make more apparent), along with adding the empty string for ::before, I see that the ::before and ::after elements are essentially (if not entirely) in the same position as the selected element itself (the “.heart” class).

I have no idea what to make of this. I’ve tried looking for answers regarding the logistics of the ::before and ::after pseudo-elements, but I can’t seem to find a satisfactory or relevant answer. Any help would be appreciated. Thanks!

<style>
.heart {
  position: absolute;
  margin: auto;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: pink;
  height: 50px;
  width: 50px;
  transform: ;
}
.heart::after {
  background-color: blue;
  content: "";
  border-radius: 25%;
  position: absolute;
  width: 50px;
  height: 50px;
  top: 0px;
  left: 0px;
}
.heart::before {
  content: "";
  background-color: yellow;
  border-radius: 50%;
  position: absolute;
  width: 50px;
  height: 50px;
  top: 0px;
  left: 0px;
}
</style>
<div class = "heart"></div>

::before and ::after actually place additional content before or after the content within the element.
Since there is not really any content in div.heart or before / after it is not obvious.
If you remove the position styling and put some content in each you’ll see it immediately.

image

<style>
.heart {

  margin: auto;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: pink;
  height: 50px;
  width: 50px;
  transform: ;
}
.heart::after {
  background-color: blue;
  content: "after";
  border-radius: 25%;
  width: 50px;
  height: 50px;

}
.heart::before {
  content: "before";
  background-color: yellow;
  border-radius: 50%;

  width: 50px;
  height: 50px;

}
</style>
<div class = "heart">heart</div>

You’ve used position:absolute. Pseudo elements like ::before and ::after don’t work any differently to any other element in this respect.

element1
element2
element3

In normal flow, these will come one after the other in the document. If you apply absolute positioning they will sit on top of each other unless you tell them where to go

I see. That makes a lot of sense. Thank you.

1 Like

You’re totally doing the right thing here btw, you just need to add some top/right/bottom/left sizes in to get the whole thing working.

@DanCouper Yeah I completed the lesson already, I was just tinkering around afterward because I was confused about what this post was referring to.

1 Like