How :before and :after creates a heart?

Tell us what’s happening:

I passed this challenge but I still don’t understand how ::before and ::after works or better yet, was able to create the heart shape. I’m lost, can someone clarify? thanks!

Your code so far


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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/responsive-web-design/applied-visual-design/create-a-more-complex-shape-using-css-and-html

1 Like

.heart:before creates an element with the specified css properties before the existing .heart element. Before meaning in the dom flow above the existing div. The :after works in the same way but obviously puts the element after the existing div.
The rectangle is made with css height and width properties.

1 Like

I was hoping for some further clarification as well. I know someone responded but their response doesn’t really help me understand how the selector really works. Could someone else explain?

Go back to that test and do the following,

comment out the following properties

"transform" from .heart ,
"border-radius" from both .heart:after and .heart:before

You can clearly see a portion of the square gets extended to the top and also to the right.
.heart:after means to add some styling after the area of .heart and similarly for .heart:before it adds some styling before the area of .heart .

If you have removed what i said above you could understand that.
In “:after” they created another square with same width and height 50px & 50px with "border-radius" and pushed it to right using the left: 25px and for “:before” they created a square with same 50px 50px width and height with "border-radius" and pushed to the top with top: -25px

Now remove the comment from "transform" , you will get a heart shape box

From the challenge…

sized
:before and :after sized and positioned

rotated
.heart rotated (:before and :after transform with it)

radius
50% border-radius to make a circle


:before and :after place things before and after the content of an elemet like a first-child, last-child

4 Likes