get-containing-block
v1.0.2
Published
A lightweight TypeScript utility to find the containing block of a given HTML Element, following the [CSS Containing Block specification](https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block).
Readme
get-containing-block
A lightweight TypeScript utility to find the containing block of a given HTML Element, following the CSS Containing Block specification.
Features
- Accurately identifies the containing block for elements with
fixed,absolute,relative,sticky, orstaticpositioning. - Handles edge cases like
transform,filter,perspective, andcontainproperties that create containing blocks. - Zero dependencies.
- Fully typed (TypeScript).
- ESM support.
Installation
npm install get-containing-blockUsage
import { getContainingBlock } from 'get-containing-block';
const element = document.querySelector('#my-element');
const { container } = getContainingBlock(element);
console.log('Containing block is:', container);Getting the Bounding Rect
You can optionally calculate the precise DOMRect of the containing block (handling padding-box vs content-box differences automatically).
const { container, rect } = getContainingBlock(element, true);
if (rect) {
console.log('Containing block rect:', rect);
}API
getContainingBlock(element, calcRect?)
Parameters:
element(HTMLElement): The element to find the containing block for.calcRect(boolean, optional): Iftrue, the result will include therectproperty. Defaults tofalse.
Returns:
- Object containing:
container(HTMLElement | null): The element serving as the containing block. Returnsnullif the containing block is the Initial Containing Block (Viewport).rect(DOMRect | undefined): The calculated bounding rectangle of the containing block. Only present ifcalcRectwastrue.
License
MIT
