Watch the short video tutorial here:
If you’re new to CSS, you’re probably already comfortable with making plenty of boxes and other four-sided shapes on your webpage, but you can also make more advanced shapes with CSS. Today will be making a triangle in CSS.
First let’s write a tiny bit of html. All you have to do is create a div.
<div class="triangle"></div>
Next, we’re just going to create a small box with with css. We’ll color it red.
.triangle {
height: 100px;
width: 100px;
background-color: red;
}
The secret to making a triangle is the “clip-path” property. Here we can use coordinates of a polygon to create a triangle in CSS.
You basically use X and Y values to make your points and lines will get drawn connecting those values.
The top-left of your div’s values are 0 0 and the bottom left are 100% 100%, or pixel sizes if you prefer.
Using this knowledge, it’s trivial to create a triangle in CSS. We can just make our CSS look like this.
.triangle {
height: 100px;
width: 100px;
background-color: red;
clip-path: polygon(0 0, 100% 0, 50% 100%)
}
And that gives us a simple red triangle.
See the Pen Triangle by josh (@jleewebdev) on CodePen.
You can play around by adding more points if you want to try and make some cool shapes.
There’s also this tool you can use to help you generate the correct values.
Leave a Reply