CSS anchor-size() Function
The anchor-size() function allows you to size an absolutely positioned element based on the dimensions of its anchor element.
The anchor-size() function is a core feature of the CSS Anchor Positioning API. While the anchor() function is used for positioning an element relative to an anchor, anchor-size() is used for sizing it. This can be useful for UI components like dropdown menus, custom select boxes, or popovers that need to match the exact width or height of the button that triggered them.
You can use the anchor-size() function within sizing properties such as width, height, min-width, max-height, and their logical equivalents (like inline-size or block-size). It evaluates to a length value representing the specified dimension of the target anchor.
Here is an example showing a dropdown menu that uses anchor-size() to ensure it is exactly the same width as its anchor button, regardless of how wide the button gets:
How It Works
The anchor-size() function takes two main arguments: the name of the anchor you want to reference, and the dimension (width or height) you want to measure.
For example, width: anchor-size(--my-anchor width) tells the browser to set the width of the positioned element to exactly match the width of the element named --my-anchor.
If you have linked the elements using the position-anchor property, you can omit the anchor name and simply specify the dimension, like width: anchor-size(width).
Providing a Fallback
Just like the anchor() function, you can provide an optional fallback value as the final argument. If the referenced anchor does not exist or cannot be resolved, the browser will use this fallback value instead.
For example: min-width: anchor-size(--my-anchor width, 250px).
Official Syntax
The official syntax of the anchor-size() function is as follows:
Possible Values
As indicated in the official syntax, the anchor-size() function accepts the following values:
- anchor-name
An optional dashed-ident (e.g.,
--my-anchor) that matches theanchor-nameproperty of the target element. If omitted, it defaults to the element specified by theposition-anchorproperty.- anchor-size
-
Specifies which dimension of the anchor element to measure. Possible values include:
- Physical dimensions:
width,height - Logical dimensions:
block,inline,self-block,self-inline
- Physical dimensions:
- length-percentage
An optional fallback length or percentage value to use if the anchor element cannot be resolved.
CSS Specifications
- The
anchor-size()function is defined in CSS Anchor Positioning (Editor’s Draft)
Browser Support
The following table provided by Caniuse.com shows the level of browser support for this feature.