Writings Tutorials

Creating Triangles Using CSS Borders

Did you know...

That you can make triangles that look like this:

Using only one element (let’s say div) and the powers of CSS?

Now you do!

How?

Let’s do this step by step.

First, let’s make a simple 100x100 square using CSS:

CSS

.triangle {
    margin: 0;
    padding: 0;
    width: 100px;
    height: 100px;
    background-color: black;
}

In making this square, we used the width and height to set the dimensions. After setting the dimensions, we added a background color. Thus, forming a square!

This time, let’s try recreating the square not using width and height, but using borders.

CSS

.triangle {
    margin: 0;
    padding: 0;
    width: 0;
    height: 0;
    border-color: black;
    border-width: 50px;
    border-style: solid;
}

In this case, we needed to do a little math. A box has four (4) borders: top, right, bottom, and left. In order to form a square which has 100px width, each border must have a 50px width.

Now that we have a square, we can create a triangle by cutting corners! It’s just like how we do it in art class. A square like this can be equally divided into four triangles, by slicing from the center of the square to the corners.

sliced-square

We cut corners by “cutting” the borders. By cutting any of the borders, we can form shapes! In this specific tutorial, we can form triangles by picking the right corners to cut. Looking at the image above, how about we cut the left, top, and right borders to form a triangle?

How do we cut them? We cut them by using the magic color value: “transparent”.

CSS

.triangle {
    margin: 0;
    padding: 0;
    width: 0;
    height: 0;
    border-color: transparent transparent black transparent; /* order: top right bottom left */
    border-width: 50px;
    border-style: solid;
}

We can make inverted triangles, too!

CSS

.triangle {
    margin: 0;
    padding: 0;
    width: 0;
    height: 0;
    border-color: black transparent transparent transparent;
    border-width: 50px;
    border-style: solid;
}

Or even double triangles!

CSS

.triangle {
    margin: 0;
    padding: 0;
    width: 0;
    height: 0;
    border-color: transparent black transparent black;
    border-width: 50px;
    border-style: solid;
}

Fun, right?

You can use these triangles in styling CSS speech bubbles, ribbons, and many more.

Thank you for reading!