CodeBlanks Logo Icon CodeBlanks

Layout API

CSS course · Expert · Lesson 15/53

Learn custom layouts with the CSS Layout API.

Intro to the Layout API

The Layout API lets you write your own layout calculation. You register a layout worklet with registerLayout('name', class). The class's layout(children, edges, constraints, style) method returns the position and size of each child.

On the CSS side you write display: layout(masonry). This reaches beyond Flexbox or Grid, for example for a masonry layout.

Limits of the Layout API

The Layout API is still experimental; it runs behind a flag in Chromium-based browsers. Before using it in production, query support with @supports (display: layout(masonry)).

The worklet runs off the main thread, so it cannot reach the DOM. It can only read the children and styles handed to it. This keeps the worklet fast and safe.

Exercise Write the CSS for a masonry feed

Complete the CSS below. The @supports block is ready; inside it add a .feed block with display: layout(masonry) and gap: 1rem.

Show example solution
/* masonry feed */
@supports (display: layout(masonry)) {
  .feed {
    display: layout(masonry);
    gap: 1rem;
  }
}

Test yourself

  1. What does the layout method of a layout worklet return?

    /* what does the layout method return? */
    • A color palette
    • A network response time
    • The position and size of each child
    • The font files
    Show answer

    The position and size of each child — Correct. The layout method returns the position and size of each child.

  2. Write the display: layout() usage

    .masonry {
      display: layout(____);
    }
    Show answer
    .masonry {
      display: layout(masonry);
    }
  3. Match the Layout API concepts

    registerLayout
    Registers the worklet
    display: layout(name)
    Usage in CSS
    layout() method
    Computes positions
    @supports
    Support query

All lessons in Expert