Pure CSS star shape [duplicate]

2019-04-18 23:46发布

问题:

This question already has an answer here:

  • How do CSS triangles work? 17 answers

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

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>

回答1:

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>

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

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

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

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

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

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

Let's visualise it!



回答2:

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.