How to Reference Inline SVG clipPath in CSS by ID

The CSS clip-path property allows developers to create complex, scalable clipping masks on HTML elements by referencing vector shapes defined in an inline SVG. By using the url(#element-id) function in CSS, the browser maps the geometric coordinates of an SVG <clipPath> element directly to the target HTML element. This article explains how this referencing mechanism works, how to configure the coordinate system for responsiveness, and how to implement the code correctly.

The url() Function Mechanism

The connection between CSS and inline SVG is established through the CSS url() functional notation. When passed an ID selector (e.g., url(#my-clip)), the browser searches the current DOM tree for an SVG element with a matching id="my-clip".

.clipped-element {
  clip-path: url(#my-clip-shape);
}

When applied, the element displaying the clip-path style will only render the portions that fall inside the geometric boundaries defined by the child shapes within that referenced <clipPath>.

Defining the Inline SVG

The vector mask must be defined inside an inline <svg> element within the HTML document. Inside the SVG, create a <clipPath> container enclosed within <defs> tags, and assign it a unique id.

<svg width="0" height="0" style="position: absolute;">
  <defs>
    <clipPath id="my-clip-shape" clipPathUnits="objectBoundingBox">
      <path d="M 0,0 L 1,0 L 0.8,1 L 0,1 Z" />
    </clipPath>
  </defs>
</svg>

<div class="clipped-element">
  <!-- Content here will be clipped -->
</div>

To prevent the source SVG from taking up space or creating visual artifacts in the layout, give it dimensions of width="0" and height="0" and position it absolutely. Avoid using display: none on the parent <svg> in older rendering engines, as this can sometimes prevent the clip path from rendering.

Managing Responsive Scaling with clipPathUnits

The behavior of the clipping mask depends heavily on the clipPathUnits attribute on the <clipPath> element:

  1. userSpaceOnUse (Default): Coordinates are interpreted as fixed pixel values based on the SVG viewport. If the target HTML element changes size, the clip path remains fixed in size and does not scale proportionally.
  2. objectBoundingBox: Coordinates are normalized to a 0.0 to 1.0 scale relative to the bounding box of the target HTML element. A value of 1 represents 100% of the element’s width or height. This setting is required for responsive designs where the mask must scale automatically with the target element.

When using clipPathUnits="objectBoundingBox", all path coordinates, circle radii, and polygon points within the <clipPath> must be written as decimal fractions between 0 and 1.