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
(Rounded Rectangle)
Using clip-path
Potential Issues
- Browser support issues: Modern browsers (Chrome, Firefox, Safari, Edge) support
clip-path. However, older browsers may not. It is always important to have a fallback using@supports:
/* 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(...);
}
}
- Child element clipping: It is important to note that if you use
clip-path, anything outside of the clipped shape will be hidden, including content that would normally overflow. This includes child elements, text, and decorative effects like shadows. Important: Even if you usez-indexandposition: absoluteon child elements, they will still be clipped to the parent's shape. For example, if you have an octagon filled with an image and want to position text over it, that text will be cut off as it is pushed beyond the octagon's boundaries. - Common mistakes: Forgetting
aspect-ratio: 1can make your octagon look stretched!