Sometimes, we need an element to be in our HTML for semantic reasons, but our life would be much easier if it just wasn’t there.
In some cases, we do not even have control over the HTML.
That is when display: contents come to the rescue.
In this short post, we’ll examine how this property behave and what are its limitations.
An “Undesired” HTML element can be tricky to work with when using flex
or grid
items.
Using display: contents
on an element will make the container disappear, and its children will act as the children of the element’s parent.
Let’s take a timeline view displaying each year using display: flex
, if we need to highlight the years after 2000, we might want to group them into a div
with a class, but that container would break the flex!
We can use display: contents
on this element to avoid that side effect:
<div class="years">
<div class="year">1996</div>
<div class="year">1997</div>
<div class="year">1998</div>
<div class="year">1999</div>
<div class="recent">
<div class="year">2000</div>
<div class="year">2001</div>
<div class="year">2002</div>
<div class="year">2003</div>
</div>
</div>
<style>
.years{
display: flex;
}
.recent{
display: contents;
font-weight: bold;
}
</style>
Having the .recent
container set to display: contents
will essentially make all .year
behave like children of .years
.
With display: contents
the box disappear, so you cannot stylize it, meaning no background, padding. You can however use color, font size and all the inline style properties.
Also, modern browsers supports it!
I'm Tom Quinonero, I write about design systems and CSS, Follow me on twitter for more tips and resources 🤙
Top comments (1)