I've found the following CSS in one of the answers here on SO and I was wondering why does it create the desired heart shape:
#heart {
position: relative;
width: 100px;
height: 90px;
}
#heart:before, #heart:after {
position: absolute;
content: "";
left: 50px;
top: 0;
width: 50px;
height: 80px;
background: red;
border-radius: 50px 50px 0 0;
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
-ms-transform: rotate(-45deg);
-o-transform: rotate(-45deg);
transform: rotate(-45deg);
-webkit-transform-origin: 0 100%;
-moz-transform-origin: 0 100%;
-ms-transform-origin: 0 100%;
-o-transform-origin: 0 100%;
transform-origin: 0 100%;
}
#heart:after {
left: 0;
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-o-transform: rotate(45deg);
transform: rotate(45deg);
-webkit-transform-origin: 100% 100%;
-moz-transform-origin: 100% 100%;
-ms-transform-origin: 100% 100%;
-o-transform-origin: 100% 100%;
transform-origin :100% 100%;
}
Please can someone explain?
CSS3 Mon Amour - A 4 Step Love Afair
There are a few steps for creating heart shape using CSS3:
Create a block-level element such as a
<div>
in your DOM and assign it withid="heart"
and apply CSS:Now using pseudo-element
#heart:before
we create a red box with one rounded edge like this:Your heart should now look like this:
Let us assign a little rotation to that by adding:
And we now get:
Already starting to come together :).
Now for the right part we basically need the same shape only rotated 45 degrees clockwise instead of counter clockwise. To avoid code duplication we attach the css of
#heart:before
also to#heart:after
, and then apply the change in position and in angle:And voilà! a complete heart shaped
<div>
:Snippet without any prefix:
Here is another idea using one element and relying on multiple backgrounds to achieve the heart shape:
How it works?
The whole shape is combined using 4 gradients: 2 gradients to create the top part and 2 for the bottom parts.
The bottom part
I simply used two
linear-gradient
to create two triangles covering the bottom part. The first one will give this:The second one is a mirror image of the first one placed on the other side.
Each gradient has a size of
[50% 50%]
, both place respectively at thebottom left
andbottom right
The top part
For the top part, I will logically use
radial-gradient
. The idea is to have two circles above each other with a truncated part at the bottom.As you can see I made the center of the circle to be at
[50% 83%]
with a radius of29%
to obtain the needed shape. Now, we need to adjust its position:We add the same gradient with a slight different position and we have the top part:
Now we simply combine both part
If you want more
We can make the shape more flexible by adding CSS variable in order to easily adjust the dimensions: