Skip to content

Instantly share code, notes, and snippets.

@bellbind
Last active October 11, 2022 00:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bellbind/78be107463982edd5566b4153546d033 to your computer and use it in GitHub Desktop.
Save bellbind/78be107463982edd5566b4153546d033 to your computer and use it in GitHub Desktop.
[CSS]Tree view with :has and :not selector
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="./tree.css" />
</head>
<body>
<label class="css-tree"><input type="checkbox" checked="checked">Tree (root)</label>
<ul>
<li>
<label class="css-tree"><input type="checkbox">Tree 1</label>
<ul>
<li>Item 1-1</li>
<li>Item 1-2</li>
<li>
<label class="css-tree"><input type="checkbox">Tree 1-3</label>
<ul>
<li>Item 1-3-1</li>
</ul>
</li>
<li>Item 1-4</li>
</ul>
</li>
<li>Item 2</li>
<li>
<label class="css-tree"><input type="checkbox">Tree 3</label>
<ul>
<li>Item 3-1</li>
<li>Item 3-2</li>
</ul>
</li>
<li>Item 4</li>
</ul>
</body>
</html>
/* show/hide children by checkbox:checked */
label.css-tree:has(> input[type=checkbox]) ~ ul {display: none;}
label.css-tree:has(> input[type=checkbox]:checked) ~ ul {display: block;}
/* tree style */
label.css-tree {text-decoration: underline;}
label.css-tree > input[type=checkbox] {display: none;}
label.css-tree:has(> input[type=checkbox])::before {content: "\25b6";}
label.css-tree:has(> input[type=checkbox]:checked)::before {content: "\25bc";}
label.css-tree ~ ul {list-style: none;}
label.css-tree ~ ul > li:not(:has(> label.css-tree))::before {content: "\25c7";}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment