Cutting Elements Into Shapes With CSS clip-path
CSS clip-path hides part of an element and leaves the area inside a shape visible. It is handy for decorative image crops, angled sections, and other designs that do not fit into a rectangle.
The original element is still rectangular. clip-path only changes what gets painted, which is worth remembering when you are debugging layout or clickable areas.
Start with the basic shapes
A circular avatar needs very little CSS:
.avatar {
clip-path: circle(50%);
}
CSS includes several basic shape functions:
inset()creates a rectangle inset from the element’s edges;circle()creates a circle;ellipse()creates an ellipse;polygon()connects a set of coordinate points;path()accepts an SVG path.
For example, this polygon turns an element into a triangle:
.triangle {
clip-path: polygon(0 0, 100% 0, 50% 100%);
}
And this ellipse is centred inside the element:
.ellipse {
clip-path: ellipse(50% 25% at 50% 50%);
}
Percentages make these shapes scale with the element, which is usually what I want for responsive images.
Which box supplies the coordinates?
You can also tell clip-path which box to use as its reference. Values include margin-box, border-box, padding-box, and content-box, along with the SVG-oriented fill-box, stroke-box, and view-box.
For most HTML examples, the default reference is enough. The box values become useful when a border or padding makes the shape line up somewhere you did not expect.
When an SVG clip is a better fit
CSS basic shapes are the simpler option for circles, ellipses, and polygons. More detailed artwork can live in an SVG <clipPath> and be referenced with url():
.illustration {
clip-path: url("/shapes.svg#my-clip");
}
That gives you more control, but it also adds another asset and more coordinates to maintain. I would start with a CSS shape and move to SVG only when the design actually needs it.
Browser support is good for common clip-path shapes in modern browsers. Complex paths and SVG references deserve testing in the browsers your site supports. Also make sure the unclipped fallback still looks reasonable; decorative CSS should not be allowed to break the content.
Enjoyed reading this?
If you found this article helpful, consider supporting my writing. Every little bit helps keep this blog going.
Related articles
- HTML Features That Can Save You Some JavaScript
Use native disclosures, dialogs, popovers, form attributes, and responsive images before rebuilding their basic behaviour.
- The HTML Details That Make Forms More Accessible
Build clearer forms with visible labels, autocomplete, connected help and errors, fieldsets, and visible focus.
- When a Control Needs aria-label
Use aria-label for genuinely unlabelled controls while keeping visible text and native elements as the first choice.