Search code examples
csscss-shapes

Pure CSS star shape


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>


Solution

  • 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