Pure CSS star shape [duplicate]

2019-04-18 22:55发布

This question already has an answer here:

There are a lot of CSS shapes shown on CSS Tricks. I am particularly surprised by the star:

Star image

How does the CSS below create this shape?

#star-five {
  margin: 50px 0;
  position: relative;
  display: block;
  color: red;
  width: 0px;
  height: 0px;
  border-right: 100px solid transparent;
  border-bottom: 70px solid red;
  border-left: 100px solid transparent;
  transform: rotate(35deg);
}
#star-five:before {
  border-bottom: 80px solid red;
  border-left: 30px solid transparent;
  border-right: 30px solid transparent;
  position: absolute;
  height: 0;
  width: 0;
  top: -45px;
  left: -65px;
  display: block;
  content: '';
  transform: rotate(-35deg);
}
#star-five:after {
  position: absolute;
  display: block;
  color: red;
  top: 3px;
  left: -105px;
  width: 0px;
  height: 0px;
  border-right: 100px solid transparent;
  border-bottom: 70px solid red;
  border-left: 100px solid transparent;
  transform: rotate(-70deg);
  content: '';
}
<div id="star-five"></div>

2条回答
叼着烟拽天下
2楼-- · 2019-04-18 23:41

Let's break it into pieces:

The yellow borders are actually set as transparent in the final product so they don't show. They are yellow here to show how the borders look.

As commented above, this answer shows the idea behind the basic triangle shape.

The div by itself:

<div id="star-five"></div>

Piece one

Combining the :before pseudo element is the same as this:

<div id="star-five">
    <div id="before"></div>
</div>

Piece two

Finally, combining the :after pseudo element is the same as this:

<div id="star-five">
    <div id="before"></div>

    <div id="after"></div>
</div>

Piece three

Now you overlap each element precisely using position: absolute; and rotate with transform as needed to get the final product:

Final product

Let's visualise it!

Animation

查看更多
在下西门庆
3楼-- · 2019-04-18 23:42

You can draw a triangle using large borders, which is what is happening there. Then they're just rotating and positioning the triangles in a star pattern.

查看更多
登录 后发表回答