If you’re looking to have nested DOM elements all participate on the same CSS grid, you’ve got Subgrid, but that just inherits grid lines. `display: contents;` can help put the elements on the same parent grid.

Take this markup:

<article class="recipe">
  <h2>
    Salted Water
  </h2>
  <div class="description">
    As delicious as it sounds! 
  </div>
  <ul class="ingredients">
    <li>1 cup water</li>
    <li>1 tsp. salt</li>
  </ul>
</article>Code language: HTML, XML (xml)

If article.recipe is display: grid;, then the only grid items are the <h2>, <div>, and <ul>, because they are the direct descendants. But it’s a reasonable ask, I think, that you’d want the <li> elements, actually, to be grid items, not the entire parent. The trick there is to tell the ul.ingredients to essentially disappear and for the rest of the DOM to behave, visually, as if it wasn’t there.

.ingredients {
  display: contents;
}Code language: CSS (css)

Here’s a layout of a slightly more complex example, but you can see how the title, description, and ingredients all share the same grid:

Live demo:

There is reason to be concerned about the list semantics and accessibility here. Lists announce themselves as lists and say how many items they have and such, and there was a period where using display: contents; would wipe that out. In reading Hidde de Vries’s More accessible markup with display: contents (which also uses a recipe as an example — I swear to god I wasn’t trying to copy Hidde it’s just what came to mind) he looks at each of the browsers and lists how it used to screw it up and that, apparently, each have been patched.

UPDATE: While it’s true the browsers were patched, after that, they regressed. 🫣

Eric says: display: contents considered harmful and goes so far as to say it can never be trusted. Bummer.


CodePen

I work on CodePen! I'd highly suggest you have a PRO account on CodePen, as it buys you private Pens, media uploads, realtime collaboration, and more.

Get CodePen Pro

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top ⬆️