Skip to main content

Contents Display

The display: contents; value in CSS is a somewhat unique and specialized display setting that essentially makes the element itself disappear from the layout, causing its children to take its place in the document flow. This can be particularly useful for semantic markup and accessibility, as it allows you to keep semantic or structural elements in the DOM without affecting layout.

Characteristics

  1. Element Disappearance: The element itself is removed from the layout and rendering tree, as if it never existed. However, it remains in the DOM.

  2. Children Inheritance: The children of the element take its place in the layout, inheriting any styles that would be inherited if the parent were still in the layout.

  3. No Box Generation: The element does not generate any boxes, so properties like border, margin, and padding on the element itself will have no effect.

  4. Accessibility: While the element is removed visually, it remains in the DOM and can still be accessed by screen readers, making it useful for improving accessibility.

  5. Pseudo-elements: Pseudo-elements associated with the element (like ::before and ::after) will not be generated.

Example-I: Basic Usage

HTML:

<div class="contents">
<span>Child 1</span>
<span>Child 2</span>
</div>

CSS:

.contents {
display: contents;
}

In this example, the <div> will not generate any box, and the <span> elements will behave as if they are direct children of the <div>'s parent.

Example-II: Grid Layout

HTML:

<div class="grid">
<div class="contents">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
</div>
</div>

CSS:

.grid {
display: grid;
grid-template-columns: 1fr 1fr;
}
.contents {
display: contents;
}
.item {
border: 1px solid black;
}

Here, the .contents div will not affect the grid layout, and the .item divs will be placed directly into the grid defined by .grid.

Best Practices

  1. Use Sparingly: This is a powerful but specialized tool. Use it only when necessary, as it can make the layout harder to understand.

  2. Browser Support: Be aware that display: contents; is not supported in Internet Explorer and has some bugs in other browsers.

  3. Accessibility: Test thoroughly for accessibility implications, especially since the element remains in the DOM.

  4. Debugging: This can make debugging more challenging, as the element won't appear in layout debugging tools.

Understanding display: contents; can be useful for specific layout and markup challenges, but it should be used carefully and tested thoroughly.