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;
transform: rotate(-45deg);
transform-origin: 0 100%;
}
#heart:after {
left: 0;
transform: rotate(45deg);
transform-origin :100% 100%;
}
<div id="heart"></div>
Please can someone explain?
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 with id="heart"
and apply CSS:
#heart {
position:relative;
width:100px;
height:90px;
margin-top:10px; /* leave some space above */
}
Now using pseudo-element #heart:before
we create a red box with one rounded edge like this:
#heart:before {
position: absolute;
content: "";
left: 50px;
top: 0;
width: 52px;
height: 80px;
background: red; /* assign a nice red color */
border-radius: 50px 50px 0 0; /* make the top edge round */
}
Your heart should now look like this:
Let us assign a little rotation to that by adding:
#heart:before {
-webkit-transform: rotate(-45deg); /* 45 degrees rotation counter clockwise */
-moz-transform: rotate(-45deg);
-ms-transform: rotate(-45deg);
-o-transform: rotate(-45deg);
transform: rotate(-45deg);
-webkit-transform-origin: 0 100%; /* Rotate it around the bottom-left corner */
-moz-transform-origin: 0 100%;
-ms-transform-origin: 0 100%;
-o-transform-origin: 0 100%;
transform-origin: 0 100%;
}
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:
#heart:after {
left: 0; /* placing the right part properly */
-webkit-transform: rotate(45deg); /* rotating 45 degrees clockwise */
-moz-transform: rotate(45deg);
-ms-transform: rotate(45deg);
-o-transform: rotate(45deg);
transform: rotate(45deg);
-webkit-transform-origin: 100% 100%; /* rotation is around bottom-right corner this time */
-moz-transform-origin: 100% 100%;
-ms-transform-origin: 100% 100%;
-o-transform-origin: 100% 100%;
transform-origin :100% 100%;
}
And voilà! a complete heart shaped <div>
:
Snippet without any prefix:
#heart {
position: relative;
width: 100px;
height: 90px;
margin-top: 10px;
}
#heart::before, #heart::after {
content: "";
position: absolute;
top: 0;
width: 52px;
height: 80px;
border-radius: 50px 50px 0 0;
background: red;
}
#heart::before {
left: 50px;
transform: rotate(-45deg);
transform-origin: 0 100%;
}
#heart::after {
left: 0;
transform: rotate(45deg);
transform-origin: 100% 100%;
}
<div id="heart"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With