How to Create a Triangle Using CSS clip-path?


On a web page, you can create a triangle easily. Use the clip-path property or even the child selector concept can be used. The clip-path allows a user to clip an element to a shape. This shape is to be set polygon to create a triangle.

Syntax

The syntax of CSS clip-path property is as follows −

Selector {
   clip-path: /*value*/
}

Create a Triangle using the clip-path

The following example illustrate CSS clip-path property. Here, we have set the clip-path shape to polygon to create a triangle. This is done using the polygon() method −

clip-path: polygon(50% 0, 100% 100%, 0% 100%);

Example

The following example uses the polygon() to create a triangle −

<!DOCTYPE html>
<html>
<head>
   <style>
      div {
         padding: 10%;
         border-radius: 2%;
         width: 10%;
         box-shadow: inset 0 0 80px violet;
         clip-path: polygon(50% 0, 100% 100%, 0% 100%);
      }
   </style>
</head>
<body>
   <div></div>
</body>
</html>

Create multiple triangles with child selector

The child selector can be used to crate multiple triangle shapes. Here, we have a div inside div i.e., div > div −

div > div {
   height: 12px;
   border-top: 40px ridge orange;
   border-right: 20px solid white;
   border-bottom: 60px ridge cornflowerblue;
   border-left: 80px solid white;
}

Example

The following example selects all <div> elements that are children of a <div> −

<!DOCTYPE html>
<html>
<head>
   <style>
      div {
         display: flex;
         margin: 10px 0 20px;   
      }
      div > div {
         height: 12px;
         border-top: 40px ridge orange;
         border-right: 20px solid white;
         border-bottom: 60px ridge cornflowerblue;
         border-left: 80px solid white;
      }
   </style>
</head>
<body>
<div>
   <div></div>
</div>
</body>
</html>

Updated on: 14-Dec-2023

386 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements