How to create triangles in CSS | Three easy ways
Recently, I was working on a project, and I wanted to create a triangle in CSS for some cool animation. So I googled it, and I found a way, but it wasn’t perfect.
So I decided to share my findings, and tell you about three different methods, their strengths, and weaknesses.
1. Triangle using Borders
First, you need to set width and height to 0px, then declare border-left / border-right, and border-top / border-bottom, depending on which way your triangle is facing.
.triangle{
width: 0;
height: 0;
border-left: 150px solid red;
border-top: 150px solid transparent;
}
This method is basically a hack, good thing is that it is supported in all browsers, however, it is very rigid and not easily adaptable. It is difficult to maintain, and combined with other content may result in unexpected behavior. Also, the problem I had with this approach, it is not easy to animate, and I problems with it.
2. Using Clip-Path
This approach is my favorite and I ended up using it in my project. It was also easy to animate, and I had no problems so far. With clip-path you can define a section to clip, and only that section of the element will be visible. To draw a polygon, you need to create a polygon using three dot positions.
.triangle{
width: 150px;
height: 150px;
background-color: blue;
clip-path: polygon(0 0, 0 100%, 100% 100%);
}
Clip-path property is well supported, it is powerful and versatile, responsive, and customizable with gradients and images, as long as they are within specified constraints. However, clip-path is not supported in any IE version, and you might make a mistake cutting off a part of the polygon.
3. Using Gradients
You can define a linear-gradient background for element, like a transition between two colors. If you make a hard change at 50%, it will create a slice-like effect.
.triangle{
width: 150px;
height: 150px;
background-image:
linear-gradient(to top right, green 50%, transparent 0);
background-repeat: no-repeat;
}
This solution works in all major browsers ( even IE 10 and up), it is responsive to container size, and text is not affected. However, this is the most tricky solution, harder to grasp, and not easily customizable.
See and play around with all of mentioned methods here: https://bit.ly/3ClQwra
4. Conclusion
It is awesome what playing around with tools like clip-path and gradients can allow you to create, and you should know how these properties work, so if you need to create something challenging, you will have tools to work with.
All of these solutions have their pros and cons, as no solution is perfect, but fear not. You just need to choose one that best fits your needs. If it doesn’t work out for you, scrap it, and try another approach.
Thanks for reading, this is my first written article, and I hope it is helpful, so please leave a like, and I’m open to constructive criticism.