Creating Shapes with CSS Clip-Path

Technical Document For: Junior Developers

The What & Why

What does the clip-path property do?

The clip-path CSS property lets us create custom shapes like octagons without needing images or complex HTML.

So why are we using it?

The Old Way: We had to use complex nested divs with border tricks to create custom shapes. As stated in the article (link at the bottom), "many of the most widely used CSS shape snippets are often dated and relying on things like magic numbers to get the shapes just right."

The New Way: Using clip-path lets us create complex shapes with one CSS property. This allows us to easily make our icons more dynamic and our layouts more visually appealing to improve user experience.

The Code

Here's how you can use clip-path to create an octagon:


        .octagon {
            width: 200px;
            height: 200px;
            aspect-ratio: 1;
    
            /*Use a custom variable to calculate corner offset for perfect 45° angles*/
            --o: calc(50% * tan(22.5deg));
    
            /*Create the octagon shape using clip path*/
            clip-path: polygon(
                var(--o) 0%, 
                calc(100% - var(--o)) 0%, 
                100% var(--o),
                100% calc(100% - var(--o)), 
                calc(100% - var(--o)) 100%, 
                var(--o) 100%, 
                0% calc(100% - var(--o)), 
                0% var(--o));
        }
    

Each pair of the variables in the clip-path corresponds to a particular point on the object.

Imagine a square. The octagon "cuts" the corners at 45° angles:

                Point 1 --- Point 2
                /                 \
            Point 8              Point 3
               |                   |
               |                   |
            Point 7              Point 4
                \                 /
                Point 6 --- Point 5
        

Live Demo

Demonstrating how you can shape containers & objects using the clip-path CSS property.

Old Way of shaping containers

Before
(Rounded Rectangle)

Using  clip-path

New way of shaping containers (Octagon)

Potential Issues


        /* Fallback for old browsers */
        .octagon {
            border-radius: 10px;
        }

        /* Octagon for modern browsers */
        @supports (clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%)) {      
            .octagon {
                border-radius: 0;
                clip-path: polygon(...);
            }
        }
    

Learn More

Source: "The Modern Guide For Making CSS Shapes" by Temani Afif, Smashing Magazine (May 2024)