Create a heart shape with Pure CSS

CSS Shorts by Shofol

CSS is fun. Often, we find it difficult and try to avoid it, even for simple tasks. We download different libraries to handle these tasks, but that can lead to performance issues. CSS is powerful but tricky. So, learning CSS tricks is both fun and effective.

Let's see the example below! We will learn how to create a heart with only one div! Yes, just a div!

Let's start coding!

At first, we will create a div. And, we will add these to CSS-

div {
  width: 100px;
  height: 100px;
  background: red;
  position: relative;
}

So, we just get this-

Now, let's start the magic. We will use the :before and :after pseudo-elements and absolute positioning. We will create two circles with these pseudo-elements. Then, we will move one circle to the top and the other to the right by half the width of the main div. In this case, the main div is 100px, so we will move the circles by 50px. The CSS will look like this:

div:before,
div:after {
  content: "";
  width: 100px; /* Same width of the main div*/
  height: 100px; /* Same height of the main div*/
  border-radius: 50%;
  position: absolute;
}

div:before {
  border: 2px solid black; /* This is only for tutorial purpose*/
  top: -50px; /*This will be the half amount of the main div*/
  left: 0;
}

div:after {
  border: 2px solid blue; /* This is only for tutorial purpose*/
  left: 50px; /*This will be the half amount of the main div*/
  top: 0;
}

By this time, I guess you have got the trick. Are you seeing a heart by bending your head? Why bend, then? Just rotate the whole thing by -45deg!

div {
  width: 100px;
  height: 100px;
  background: red;
  position: relative;
  transform: rotate(-45deg);
}

See the result for real!

For the tutorial purpose I had used the border colors on :before and :after elements. You don't need those. You can just use the background color of those elements as the main div. And, you will get a perfect heart like yours!

The actual CSS will be-

div:before,
div:after {
  content: "";
  width: 100px;
  height: 100px;
  border-radius: 50%;
  position: absolute;
  background:red;
}

div:before {
  top: -50px;
  left: 0;
}

div:after {
  left: 50px;
  top: 0;
}

And, we get this-

See the step-by-step guide on this Codepen-

Bonus!

How about making the heart beat? No worries! CSS is there. We can do that with very simple animation. We will scale the heart by 1.2 and then revert back to normal and we will run the animation for infinite. Check the live example here-

That's it for now! Let me know if you like the tutorial and knock me anytime to have a chat!

Follow me on other platforms-
Twitter Handle
LinkedIn Handle

If you like the article, you can Buy me a coffee ☕. I'm also available for new Frontend Projects.