What is display contents in CSS: Explanation and Usage
display: contents property in CSS makes an element disappear visually but keeps its child elements visible and part of the layout. It removes the element's box, so the children behave as if they were direct children of the parent element.How It Works
Imagine you have a box inside another box, but you want the inner box to vanish so only its contents show up, as if they were directly inside the outer box. That's what display: contents does in CSS. It removes the element's own box but keeps its children visible and part of the page layout.
This means the element itself doesn't take up space or affect layout, but its children behave normally. It's like peeling off a wrapper from a gift and showing the gift inside without the wrapper getting in the way.
This is useful when you want to keep your HTML structure for organization or accessibility but don't want extra boxes messing with your design.
Example
This example shows a parent with a child element using display: contents. The child’s box disappears, but its text remains visible and styled by the parent.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Display Contents Example</title> <style> .wrapper { border: 2px solid blue; padding: 10px; width: 200px; } .inner { display: contents; font-weight: bold; } </style> </head> <body> <div class="wrapper"> <div class="inner"> This text is inside the inner div. </div> </div> </body> </html>
When to Use
Use display: contents when you want to keep your HTML elements for structure or accessibility but don't want their boxes to affect layout or styling. For example:
- Removing extra wrappers that interfere with CSS Grid or Flexbox layouts.
- Improving accessibility by keeping semantic elements without visual clutter.
- Flattening nested elements so child elements behave as if they are direct children of a grandparent.
It helps keep your code clean and your design simple without changing your HTML.
Key Points
display: contentsremoves the element’s box but keeps its children visible.- Children behave as if they are direct children of the removed element’s parent.
- Useful for layout control without changing HTML structure.
- Not supported in some older browsers, so check compatibility.
- Does not affect accessibility roles or semantics of the element.
Key Takeaways
display: contents removes an element’s box but keeps its children visible and in the layout.