How to create a heart shape using CSS?

后端 未结 2 530
离开以前
离开以前 2020-12-05 15:13

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:

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-05 15:31

    Here is another idea using one element and relying on multiple backgrounds to achieve the heart shape. You can also easily adjust the size by only changing the width:

    .heart {
      width:200px;
      background:
       radial-gradient(circle at 60% 65%, red 64%, transparent 65%) top left,
       radial-gradient(circle at 40% 65%, red 64%, transparent 65%) top right,
       linear-gradient(to bottom left, red 43%,transparent 43%) bottom left ,
       linear-gradient(to bottom right,red 43%,transparent 43%) bottom right;
      background-size:50% 50%;
      background-repeat:no-repeat;
      display:inline-block;
    }
    .heart::before {
      content:"";
      display:block;
      padding-top:100%;
    }

    You can also use mask and you can have any kind of coloration:

    .heart {
      width:200px;
      display:inline-block;
      -webkit-mask:
         radial-gradient(circle at 60% 65%, red 64%, transparent 65%) top left,
         radial-gradient(circle at 40% 65%, red 64%, transparent 65%) top right,
         linear-gradient(to bottom left, red 43%,transparent 43%) bottom left ,
         linear-gradient(to bottom right,red 43%,transparent 43%) bottom right;
      -webkit-mask-size:50% 50%;
      -webkit-mask-repeat:no-repeat;
      mask:
         radial-gradient(circle at 60% 65%, red 64%, transparent 65%) top left,
         radial-gradient(circle at 40% 65%, red 64%, transparent 65%) top right,
         linear-gradient(to bottom left, red 43%,transparent 43%) bottom left ,
         linear-gradient(to bottom right,red 43%,transparent 43%) bottom right;
      mask-size:50% 50%;
      mask-repeat:no-repeat;
      background:linear-gradient(red,blue);
    }
    .heart::before {
      content:"";
      display:block;
      padding-top:100%;
    }


    How does it works?

    The whole shape is combined using 4 gradients: 2 gradients to create the top part and 2 for the bottom parts. each gradient is taking 1/4 of size and placed at a corner.

    Use a different color for each gradient to clearly identify the puzzle

    .heart {
      width:200px;
      background:
       radial-gradient(circle at 60% 65%, red  64%, grey 65%) top left,
       radial-gradient(circle at 40% 65%, blue 64%, black 65%) top right,
       linear-gradient(to bottom left, green 43%,black 43%) bottom left ,
       linear-gradient(to bottom right,purple 43%,grey 43%) bottom right;
      background-size:50% 50%;
      background-repeat:no-repeat;
      display:inline-block;
      border:5px solid yellow;
    }
    .heart::before {
      content:"";
      display:block;
      padding-top:100%;
    }

提交回复
热议问题