Skip to content

Instantly share code, notes, and snippets.

@johnhunter
Created March 9, 2023 22: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 johnhunter/42e322038f0569ad9a824fe9a1eb56d4 to your computer and use it in GitHub Desktop.
Save johnhunter/42e322038f0569ad9a824fe9a1eb56d4 to your computer and use it in GitHub Desktop.
Using has to highlight adjacent elements
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Adjacent hover highlight</title>
<style>
body {
font-family: sans-serif;
}
ul {
display: grid;
list-style: none;
grid-template-columns: 1fr;
padding: 2rem;
gap: 0.25rem;
}
li span {
display: block;
background: #eee;
padding: 1rem;
transition: all 0.3s ease-in-out;
}
li:hover span, /* highlight row */
li.main:hover + li.sub span, /* highlight following row */
li.main:has(+ li.sub:hover) span /* highlight previous row */ {
background: red;
color: white;
}
</style>
</head>
<body>
<ul>
<li class="main"><span>one</span></li>
<li class="sub"><span>- one</span></li>
<li class="main"><span>two</span></li>
<li class="sub"><span>- two</span></li>
<li class="main"><span>three</span></li>
<li class="sub"><span>- three</span></li>
</ul>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment