In the example below when we hover any row from group 1, all group 1 rows change colour. I want to apply this same logic for N
number of groups.
Let’s say we have 300 of these groups of 3 rows. How can we achiveve this highlighting for each group without copy and pasting the CSS rule 300 times.
Can this be achieved with pure css?
.parent:has(.group-1:hover) .group-1 {
background-color: blue;
}
<body class="parent">
<p class="group-1">Group 1</p>
<p class="group-1">Group 1</p>
<p class="group-1">Group 1</p>
<p class="group-2">Group 2</p>
<p class="group-2">Group 2</p>
<p class="group-2">Group 2</p>
<p class="group-3">Group 3</p>
<p class="group-3">Group 3</p>
<p class="group-3">Group 3</p>
</body>
3
Answers
you can give all of them 1 more class name besides their specific class names.
and also if you can do this:
this selection, let you select all of the parent/body children.
you can also select all
<p></p>
element if you have use<p></p>
tag just here.Well if you can not alter the HTML to make them wrapped in groups, you can dynamically create your CSS so you are not manually writing out all the rules.
If you definitely know that each group has exactly 3 entries you can use a combination of nth-child, before pseudo element (to hold the background) and z-index.
This snippet confines the hover to the first element in a group, but it appears to the user that they are hovering on the group in general as it is a before pseudo element on the first element that is overlaying the others in the group.
Aside: whether you would actually want to do this in practice is another matter. While it does achieve the highlighting, it is IMO a bit hacky and I’d probably go for a bit of JS just to make it more obvious what is going on ie. simpler to maintain.