DEV Community

loading...

Make triangles with borders in CSS

nazanin_ashrafi profile image Nazanin Ashrafi ・2 min read

At first it may seem like making triangles with CSS might be hard...
Well...
For me it kinda was. but when you understand how to do it right you'll see it wasn't hard at all
So let's begin :

If we do this :

{
width: 200px;
height: 200px;
border-bottom: solid 25px red;
border-right: solid 25px green;
border-left: solid 25px blue;
border-top: solid 25px yellow;
}

The results would look like this :
triangle

You see how each border has a sharp point?
And now we set the height and width to zero :

{
width: 0;
height: 0;
border-bottom: solid 25px red;
border-right: solid 25px green;
border-left: solid 25px blue;
border-top: solid 25px yellow;
}

with setting the height and width to zero we removed the space between borders and the sharp points got sharper ,then all came close together and now we have 4 triangles.

You may ask "okay how do I make just one triangle? I don't need four of them"!

It's easy. we'll make a triangle that its sharp point faces up :
{
width: 0;
height: 0;
border-bottom: rgb(255, 139, 251) solid 200px;
border-left: transparent solid 200px;
border-right: transparent solid 200px;
}

So what happened here?
Since I wanted the sharp point to be at the top I had to give it border-bottom and then border-left and border-right.

As you can see we have 3 triangles here, in order to make it just one we have to make the left and right triangles invisible.
And the trick is we have to set them to transparent.

If you want the sharp point to face down you need to give it border-top and set the border-left and border-right to transparent:
{
width: 0;
height: 0;
border-top: 100px solid rgb(0, 162, 255);
border-left: 100px solid transparent;
border-right: 100px solid transparent;
}



We can even make triangles that face top-left, top-right, bottom-left and bottom-right



I've prepared a CSS file and live preview. you can check it out HERE

You can also check out this cool animation on codepen

Discussion

pic
Editor guide
Collapse
atakanatici profile image
Collapse
nima_owji profile image
Nima Owji

Really cool

Collapse
nazanin_ashrafi profile image
Nazanin Ashrafi Author

Thanks 🙌🙌🌹

Collapse
programmerbyda1 profile image
ProgrammerByDay

So basically it's a square with one giant border and three transparent borders. Is that right?

Collapse
nazanin_ashrafi profile image
Nazanin Ashrafi Author

Well yeah something like that but we don't really need add 3 transparent borders, just 2 transparent borders do the job.
Adding extra invisible border would only take some more space