CSS display:contents basic introduction

In this article we will have a look at a basic introduction of display:contents in CSS. We need to learn about this useful property with some examples.

What is display:contents?

We take a look at how Manuel Rego takes a stab at explaining it :

display:contents makes that the div doesn’t generate any box, so its background, border and padding are not rendered. However the inherited properties like colour and font have effect on the child (span element) as expected.

Generally display: contents makes the container that we apply this property, to get disappeared.

display:contents as an example

Firstly we will take a look at this example from Rachel Andrew. We will see how giving this property to the outer element makes all box styling disappear:

As a result we loose all the box style such as border and background and padding and so on in the outer box. So display: contents is good if we need an element for the sake of semantic HTML but not as a styled element.

Here is another example with FlexBox

Practically we could use display:contents to change the HTML to make our own layouts. In this example from Rachel Andrew we have the inner two boxes wrapped in a container. Using display: contents we remove the box and make those two inner boxes child of Flexbox container:

Accessibility issue

However we better know that browsers will remove any element with a display:contents set on it from the accessibility tree. Therefor this will cause the element and all its descendant elements to no longer be announced by screen reading technology.

Although display:contents still doesn’t have full support in browsers but we better start learning and trying it. Another discussion is to use it for subgrids. I will leave that for another post as it is a complete subject by itself. Thanks for reading.

© 2019
Azadeh Faramarzi

This site is created and maintined by Azadeh Faramarzi , A passionate developer, sport and code lover who loves to share and write when she has some time.