CSS

How to make a triangle with CSS – simple and fast

July 6, 2021

How to make a triangle with CSS – simple and fast

Using pure CSS as much as possible can be beneficial to our code, so instead of creating a triangle image learn to make a triangle with pure CSS

make a triangle with CSS cover

What is the idea behind the triangle with CSS?

To create this feature we will use a technique with borders, so the elements will not have width or height through width and height.

Its size will come from the border property, as well as the color of the triangle.

So the CSS triangle is always composed by the border in the reverse direction we want it to appear.

For example, the upward triangle is composed of the border-bottom, and to make the tip of the triangle we need the left and right borders to be transparent.

Let’s see in practice?

Triangle code with CSS:

Here we are going to create four triangles with CSS, up, right, down, and left

First the HTML:

<div id="triangle-up"></div>

<div id="triangle-to-right"></div>

<div id="down-triangle"></div>

<div id="triangle-to-left"></div>

We created four divs with an id for each triangle, now see the CSS:

div {
    display: inline-block;
    margin-right: 50px;
}

#triangle-up {
  width: 0; 
  height: 0; 
  border-left: 25px solid transparent;
  border-right: 25px solid transparent;
  border-bottom: 25px solid #5386E4;
}

#triangle-to-right {
  width: 0; 
  height: 0; 
  border-top: 25px solid transparent;
  border-bottom: 25px solid transparent;
  border-left: 25px solid #4C4B63;
}

#down-triangle {
  width: 0; 
  height: 0; 
  border-left: 25px solid transparent;
  border-right: 25px solid transparent;
  border-top: 25px solid #949396;
}

#triangle-to-left {
  width: 0; 
  height: 0; 
  border-top: 25px solid transparent;
  border-bottom: 25px solid transparent; 
  border-right:25px solid #ABA8B2; 
}

Here the theory explained in the introduction was applied, to create the triangles with CSS we left the elements with 0 in height and width

And we define the edges of the shapes that we point the triangles, always in the opposite direction of the desired one, see the final result:

Imagem

That way we will have an optimized code because images would take much longer to load than a simple CSS

In addition, the code is easy to maintain, just by changing the rules we can change this triangle

The image, on the other hand, should be generated again with each change, making the process time-consuming and dependent on more people

If you have any questions leave them in the comments, we will respond as soon as possible.

Conclusion

And that’s it for today, until the next post!

Also, check out our free HTML and CSS course on YouTube by clicking here! Where we create a site from 0 to responsive 😀

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x