How to draw a heart using CSS
Use two rectangles to cut rounded corners to tilt the displacement and merge into a heart shape
Draw a Rectangle
This rectangle is half of the heart
<div class="setp1"></div>
Copy the code
.setp1 {
width: 50px;
height: 100px;
background: red;
}
Copy the code
Cut the rounded corner
Cut a rounded corner to make it more like a heart
<div class="setp2"></div>
Copy the code
.setp2 {
width: 50px;
height: 100px;
background: red;
border-radius: 50% 50% 0 0
}
Copy the code
Step 3 Tilt
Tilt to complete the half of the heart
<div class="setp3">
<div class="setp2"></div>
</div>
Copy the code
.setp2 {
width: 50px;
height: 100px;
background: red;
border-radius: 50% 50% 0 0
}
.setp3 {
position: relative;
left: 30px;
}
.setp3 > div {
transform: translate(-18px,0) rotate(-45deg);
}
Copy the code
Step 4 Merge
The other half does the same and merges into one heart
<div class="setp4">
<div class="setp2 left"></div>
<div class="setp2 right"></div>
</div>
Copy the code
.setp4{
position: relative;
left: 30px;
height: 120px;
}
.setp4 > div {
position: absolute;
left: 0;
}
.left{
transform: translate(-18px,0) rotate(-45deg);
}
.right{
transform: translate(18px,0) rotate(45deg);
}
Copy the code
Step 5 Optimization
We found a heart with 3 divs is too much redundancy let’s optimize it.
Replace redundant structures with pseudo-classes.
<div class="heart">
</div>
Copy the code
.heart{
position: relative;
left: 30px;
}
.heart:after {
border-left: 25px solid red;
border-right: 25px solid red;
border-top: 50px solid red;
border-bottom: 50px solid red;
border-radius: 50% 50% 0 0;
content: "";
position: absolute;
top: 0;
left: 0;
transform: translate(-18px,0) rotate(-45deg);
}
.heart:before {
border-left: 25px solid red;
border-right: 25px solid red;
border-top: 50px solid red;
border-bottom: 50px solid red;
border-radius: 50% 50% 0 0;
content: "";
position: absolute;
top: 0;
left: 0;
transform: translate(18px,0) rotate(45deg);
}
Copy the code
Results the preview
(after)