How to Create Triangle in HTML and CSS

In this tutorial, we will learn how to create triangle in HTML and CSS. Shapes are not something that you are going to create in your everyday web development job. But since it’s a part of the job, you must be aware of how to create one.

It is very tricky to create a triangle, but with the use of some CSS properties, we can easily create nice triangles. Keep in mind that when you are creating a triangle, you have to set the borders to match the triangle and the height and width should be zero on the element.

In the following example, we will demonstrate how you can create a triangle using CSS. Please have a look over the code example and the steps given below.

HTML

  • In the HTML file, we have one empty div element with a class name (.triangle).
  • In the head element, we have added a stylesheet (style.css) using the link element.
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Triangle</title>
    <link rel="stylesheet" href="./style.css">
</head>

<body>
    <div class="triangle"></div>
</body>

</html>

CSS

  • We are selecting the div using the class name (.triangle) and setting the margin property value to 0 auto to horizontally center align the div.
  • The height and width property value to 0, border-left and border-right property value to 40px solid transparent, and border-bottom property value to 80px solid red. As a result, it will create a triangle.
.triangle {
    margin: 0 auto;
    width: 0;
    height: 0;
    border-left: 40px solid transparent;
    border-right: 40px solid transparent;
    border-bottom: 80px solid red;
}