CSS-23Optional
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 Select elements by their own class.
Examples
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
- CSS-16 Select elements by their own class in HTML and CSS
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/html-css/html-structure-and-reuse/no-wrapper-divs">Agent Wranglers HTML and CSS playbook</a>. In code you write, add a comment next to it with the same link.