display: contents
When adding display: contents
to a parent element:
- The parent element is not rendered
- Its chidren act as if the parent never existed, but styles will still be inherited
The MDN docs state that the parent element is “replaced by [its] pseudo-box and their child boxes.”
.parent {
border: 5px solid mediumpurple;
color: cyan;
background-color: rgba(255, 255, 0, 0.25);
}
.parent .child {
border: 5px dashed red;
}
Normal: |
child |
With |
child |
A particularly handy use case that I encountered for this property is as follows:
The image horizontally scrolls if on mobile
By default / on the desktop:
- Each column would be its own
flex
container and reside inside a parent (let’s call this Apple). Widths would be set accordingly. - The elements’ parent (and thus flexbox layout) would be one of the column
On a mobile viewport:
- Set Apple to
flex-direction: column
- Set the columns’ display to
contents
. The elements’ new “parent” is Apple, in the sense that Apple’s flex styles would apply to these items (flexbox applies to direct children). - The
order
property can be used to set the order of the elements.
*As of writing, elements with this display
value will be removed from the “accessibility tree”, meaning that the element itself is not visible to screen readers. This does not comply with the CSSWG specification.