CSS clip-path property
The primary purpose of the clip-path
property is to create a clipping region that sets which part of an element should be visible. Think of it as a mask where only the defined region is shown, and everything outside of it is hidden.
Syntax and Values
The basic syntax for the clip-path
property is:
clip-path: <value>;
The values it can take include:
- Keyword values: The most straightforward is
none
, which means no clipping is applied. <clip-source>
values: For example,url(resources.svg#c1)
, which references a specific SVG clipPath element.<geometry-box>
values: These includemargin-box
,border-box
, etc., which define the reference box for the clipping region.<basic-shape>
values: These are predefined shapes likeinset()
,circle()
,ellipse()
,polygon()
, andpath()
.
Using Basic Shapes
Basic shapes provide a simple way to define clipping regions:
inset()
: This defines an inset rectangle. For instance,clip-path: inset(10% 20% 30% 40%)
clips the element with the specified offsets.circle()
: It defines a circle. Example:clip-path: circle(50% at 50% 50%)
creates a circle centered in the middle of the element.ellipse()
: Like circle but for ellipses.clip-path: ellipse(50% 25% at 50% 50%)
creates an ellipse.polygon()
: Defines a polygon.clip-path: polygon(0% 0%, 100% 0%, 50% 100%)
creates a triangle.path()
: This is for more complex shapes using SVG path definitions.
Geometry Boxes
The reference box for the basic shape determines the coordinates’ system:
margin-box
: Outermost box, including margins.border-box
: Includes the border.padding-box
: Up to the padding edge.content-box
: Just the content.fill-box
: Uses the object bounding box as reference.stroke-box
: Considers the stroke of the SVG.view-box
: Uses the SVG’s view box.
Practical Examples
When using clip-path
with HTML, it’s applied directly to the element. With SVG, it references a clipPath
element. For instance, a circle clip in HTML might be clip-path: circle(50%)
, while in SVG, you’d define a clipPath
element and reference it with url(#myClip)
.
Comparatively, SVG offers more flexibility, especially for complex shapes, but HTML is more straightforward for simple clippings.
Browser Compatibility
Most modern browsers support the clip-path
property. However, it’s always a good idea to check compatibility tables and test across browsers. For unsupported browsers, consider fallback designs or polyfills.
Enjoyed this post? Please grab the RSS feed. You can also buy me a coffee.