How to Draw Triangles in CSS3

One of the many advantages of CSS3 is that it makes web pages look better without always having to use image files. This means some basic graphic functionality is achievable solely through CSS3. Drawing shapes with CSS3 is one such advantage. While shapes like squares and rectangles are relatively simple, drawing a triangle requires a bit more effort but can nevertheless be done in CSS3.

CSS3 Code for a Triangle

Here is the CSS3 code for a triangle with the apex at the top and the base at the bottom.

css triangle

For a triangle with its apex at the bottom and base at the top the code is as follows.

How do CSS3 triangles work?

In order to understand how a CSS3 triangle works, it may be easier to look at it through a CSS3 square with different colored borders.

Here is the code:

css3 triangle

Your will see a square of 200 pixels by 200 pixels with a solid border. The top border is yellow, the right is blue, the bottom is red and the left border is green. This is essentially four triangles with their apices meeting to form a square from their bases.

Now we remove the top border to get a rectangle. Here is the new code:

css3 triangle

The yellow border at the top is no longer visible. Now we remove the borders at the top and left and right side by setting it to transparent with this code:

css triangle

The result is the red triangle.

Another way of achieving the same effect is to draw a rectangle and do a transform rotate. However, this is more complicated. It also has browser compatibility issues but may be the better option when you need a responsive triangle and a triangle with borders.

Leave a Comment