CSS triangles. How does it work?

How to draw CSS triangle — step by step visualization

Anna Prykhodko
2 min readFeb 16, 2021
Photo by Chris Ashe on Unsplash

We are used to the fact that everything in CSS is rectangles. It is relatively easy to understand the concept of a circle, create round borders — get a circle or an oval. But what about the rest of the shapes?

To create a triangle in CSS, you just have to search and find code like this:

.arrow-up {
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 5px solid black;
}

But this code doesn’t look like a triangle in any way, it looks more like magic. But what if you need not the pointed top triangle, but, for example, turned to the right? You can change the borders a little, their colors and size. You will probably achieve what you need, but it’s always better to understand how it actually works, so let’s figure it out.

First, let’s draw a simple 50x50px rectangle with a background-color and 50px thick colored borders.

Yellow rectangle 50x50 with pink borders

It still doesn’t look like a triangle, but let’s set a different color for each border.

Yellow rectangle 50x50 with multi-colored borders

Now you can see that one border is a trapezoid, the top base of which is 50 pixels — this is the width/height of our rectangle. Bottom base 150 pixels — rectangle size + width of adjacent borders on both sides.

The triangle is already very close, we just need to reduce the top base of the trapezoid to zero, that’s why we will remove the rectangle's size.

Rectangle 0x0 with multi-colored borders

Now we have 4 triangles facing in different directions. Different borders — different triangles. If we make three of four borders transparent, we will get one triangle. It is better to make the opposite border’s width equal to zero for the convenience of centering.

So if you need a triangle turned to the right, you need to set the size and color of border-left, set the border-right size to zero or/and make it transparent, the rest of the borders must have size but be transparent.

Four multi-colored triangles

Knowing this feature of the borders, you can create trapezoids or increase the triangles’ width or height, rotate them in different directions, and change the sides' slope.

Four different shapes

CSS is a very flexible language that allows you to solve problems in many different ways. It offers many possibilities that are not always obvious. But understanding the basics of the language and the principles of rendering allows you to solve everyday tasks better.

I hope this short article was helpful.
See you next time!
🤹🏻‍♀️

--

--

Anna Prykhodko
Anna Prykhodko

Written by Anna Prykhodko

Front-end developer · Kyiv 🇺🇦

Responses (1)