Use display: contents to flatten a wrapper element
display: contents makes an element not generate a box of its own. Its children are laid out as if they were direct children of its parent:
<div style="display: flex">
<div>A</div>
<div style="display: contents">
<div>B</div> <!-- flex item of the outer div -->
<div>C</div> <!-- flex item of the outer div -->
</div>
</div>
The outer flex container now sees three items (A, B and C) instead of two.
Reordering nested elements
Flexbox and grid can only position and order their direct children. When an element you want to move is nested inside a wrapper, you can’t move it out without changing the markup.
For example, a card with an image and a text column, where on mobile the title should sit above the image while the rest of the text stays below it:
<article class="flex flex-col md:flex-row">
<img class="order-2 md:order-none" src="...">
<div class="contents md:block">
<h2 class="order-1 md:order-none">Title</h2>
<div class="order-3 md:order-none">Description...</div>
</div>
</article>
On mobile the wrapper is flattened, so the title, the image and the description are all flex items of article and order can arrange them. From md up, md:block brings the wrapper back and you get the regular two-column layout. You don’t need to duplicate the title and toggle it with hidden.
Gotchas
- The element’s own box styles (
padding,margin,border,background,width) no longer apply, so move them to the children. - Inherited properties like
colorandfontstill pass through to the children. orderchanges only the visual order. Screen readers and keyboard focus still follow the source order.- Avoid it on semantic elements like
button,ulortable. Older browsers removed them from the accessibility tree.
If you like this article consider tweeting or check out my other TILs.