CSS Christmas

CSS Grid's Best Friend

A 2 minute read written by
Sondre Kongsgård

Previous postNext post

There is a display property that goes hand-in-hand with CSS grid: display: contents. With this property you can keep good HTML semantics when using CSS grid. Let's see how.

Let's say you're writing a blog, and want an overview page of all the posts you've written. You might choose the following markup:

    <h1>My Awesome Blog</h1>
        <h2>Title #1</h2>
        <p>Ingress #1</p>
        <h2>A title that spans multiple lines</h2>
        <p>Ingress #2</p>
        <h2>Title #3</h2>
        <p>Ingress #4</p>
        <h2>Title #4</h2>
        <p>Ingress #4</p>

If you want to present this in e.g. a two-column layout, a good choice would be to set display: grid on the section tag:

However, you might stumble into a challenge if you also want both the title and the ingress of each article to align nicely with each other. In that case it might be tempting to remove the <article> tag from the markup, but instead you may simply add display: contents on this tag, along with some extra CSS to specify the flow of the elements in the grid:

See how Ingress #1 is now vertically aligned with Ingress #2? 🤩

When the display property display: contents is added to the <article> tag, the h2 and p elements act as if they were direct children of the grid.

So next time you're working with CSS grid, see if you can utilize its companion display: contents to get the grid just the way you want it - while keeping the HTML semantics in tip-top shape.

PS: display: contents also enables you to use CSS grid with tables, which potentially gives you superpowers over the common table-layout: fixed approach (see the link "Flexible data tables" for an in-depth blog post). Here is a simple example:

Read the next post

Read more outside the calendar