How To Create Triangles With HTML/CSS?

Triangles are useful for creating different types of design artifacts on a website, particularly speech balloons. HTML/CSS has no explicit way of creating triangles therefore some people use triangle images instead. However there is a small hack with which one can create triangles without any images.

There is a property in CSS called ‘border’. It is usually used to draw a border around a box. The interesting fact about ‘border’ property is that it all the four corner joints are angular. To understand it, create a div and apply following style on it.

<div></div>
div {
    width: 40px;
    height: 40px;
    border-width: 16px;
    border-color: red green blue yellow;
    border-style: solid;
}

You should see something like this:

Now let’s make borders on left, top and right transparent and reduce the width and height of the div to 1px.

div {
    width: 1px;
    height: 1px;
    border-width: 16px;
    border-color: transparent transparent blue transparent;
    border-style: solid;
}

You should see something like this:

You can play with ‘border-width’ property to change the angles of the triangle.

div {
    width: 1px;
    height: 1px;
    border-width: 1px 16px 16px 0px;
    border-color: transparent transparent blue transparent;
    border-style: solid;
}


Similarly, you can play around with different values of ‘border-‘ properties to make different shapes and forms.

div {
    width: 1px;
    height: 1px;
    border-width: 0px 16px 16px 0px;
    border-color: transparent red red transparent;
    border-style: dotted;
}

Published by

Umar Ashfaq

Umar Ashfaq is a full-stack web developer. His core strength is building neat UIs with JavaScript on web but he also enjoys server side Java, NodeJS and Objective C. Follow him on twitter @umarashfaq87

5 thoughts on “How To Create Triangles With HTML/CSS?”

  1. Is it possible to create triangles with just CSS? I want to be able to show the arrow automatically without having to put on html?

    Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *