loading...
Cover image for πŸ’… How to create a triangle in CSS

πŸ’… How to create a triangle in CSS

codesandtags profile image Edwin Torres ・2 min read

A couple of days before, I had to face this common challenge, however, there are many solutions (using images, using divs, and using pseudo-elements with and empty content). For me, the best solution was using pseudo-elements, so that here is my solution.

If you want to read more about this common pattern, please review this article in CSS Tricks (One of the best pages for CSS Content).

Understanding ::before and ::after pseudo-elements in CSS

In few words a pseudo-element is :

A CSS pseudo-element is a keyword added to a selector that lets you style a specific part of the selected element(s). For example, ::first-line can be used to change the font of the first line of a paragraph.

Creating the triangle

After understanding the above concept, it means we can add some content, or create another element given a selector.
In our case, if we define a border-width and we have an empty content, the border will start from the center of the element.

Then, pretty much we need to play with the border-color, border-width and the position:absolute to create our triangle. Below, you will find a couple of examples in my codepen.

What's the next?

Well, I think that's all using a short example. Given the above examples, you can add letters, transformations, animations, and whatever you can imagine, using the pseudo-elements.

To get a complete list, please check the documentation and don't forget review the compatibility with browsers.

If you want to see my original post, you're welcome here.

Cheers and keep learning! 🍻

Posted on May 20 by:

codesandtags profile

Edwin Torres

@codesandtags

β™₯️ Full-Stack Software Developer, I really love coding πŸ‘¨πŸ»β€πŸ’» travel ✈️ and share the knowledge.

Discussion

markdown guide