You've probably been there before; some CMS spews out the "perfect" HTML-structure (with lot's and lot's of
div elements) and you can't get the DOM-structure to work with the designer's design. Or semantics call for things to be grouped together, while you don't want these elements to be grouped visually. This won't be a problem anymore, since the future is here! Meet
display: contents; will get an element to only display it's children and pseudo-elements. For all layout purposes it means the element itself wil cease to exist. The means that grid and flex, for instance, will ignore the element with
display: contents; and instead will skip straight to it's children and affect them. Let's have a look at a little demo.
Sorry your browser does not seem to support
display: contents;. For more info on browser support check caniuse.com
Well isn't that nifty!
In the demo above, you can see the effect
display: contents; has when used in combination with, in this instance, flexbox. We have two groups of presents which we just want to show as one list. Our CMS however can only output these different groups as separate
ul elements, but
display: contents; saves our bacon!
What else can you use it for?
You can think of
display: contents; removing one or more elements from the layout flow without changing the DOM. Keep in mind that any visual styling like margins, paddings, backgrounds will also not work. Their values will still be inherited though (it it's an inheritable property that is).
This enables you to group elements by using a different ancestor as parent in the layout. It also works the other way around; you now have more freedom in setting up the HTML. If semantics call for a certain structure in which your element of choice should be enclosed with five wrappers, and three containers, while still being a part of the grid structure of the webpage, this monstrocity can now actually come into being. Whether that's a good thing or not is debatable…
display: contents; currently works in very few browsers. Firefox is the only production browser that suppports it. It also works in the technology preview of Safari, and in current Chrome but behind the experimental web features flag enabled.
- Chrome Behind flag
- Safari Technology Preview
Demo source code
Do you want to dig in the nitty-gritty of this demo, check out the source files: