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.