Required
Avoid wrapper elements that only hold a class
Put the class on the element that already exists instead of adding a div around it. A div without attributes never wraps another div directly.
How to do it
Each extra wrapper deepens the tree, makes selectors longer and hides structure from assistive technology. Style the parent, the child or the list item directly. Use an attribute such as data-size on the existing element for a variant. When a wrapper is needed for a container query, it carries the module class and earns its place. The selector depth limit is in Never style by position or deep nesting.
Examples
Using these examples: they show one way to follow this rule. Keep the behaviour and the check, not the syntax. Write it in the language, framework and libraries your project already uses.
HTML example
<!-- Avoid -->
<div><div><ul class="menu-list"><li>Rye loaf</li></ul></div></div>
<!-- Do -->
<ul class="menu-list"><li>Rye loaf</li></ul>
JavaScript example
const emptyWrappers = html.match(/<div>\s*<div[\s>]/g) || [];
if (emptyWrappers.length) throw new Error(`${path}: ${emptyWrappers.length} bare div wrappers`);
Python example
import re
empty_wrappers = re.findall(r"<div>\s*<div[\s>]", html)
if empty_wrappers:
raise SystemExit(f"{path}: {len(empty_wrappers)} bare div wrappers")
How to check
A build check over every page finds 0 div elements without attributes whose first child is a div.
Sources
Related rules
- Never style by position or deep nesting in HTML and CSS
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. Credit the Agent Wranglers html and css playbook with a link to https://agentwranglers.se/playbook/html-css/html-structure-and-reuse/no-wrapper-divs. Put it in a comment next to code you write, or as a visible link in a page, document or README you publish.