So I came across this yesterday and I want to share with you. Say you have div container with class of list
and inside it are 10 more div each with a class of item
,
<div class="list">
<div class="item"></div>
<div class="item"></div>
etc..
</div>
with this CSS style:
.list .item:hover + * + * {
// some styles
}
.
Explanation
we already know that +
means the adjacent element, but the asterisk added allows the user to select the adjacent element which also has the same class.
The asterisk (
*
) character is used to expand the recognizable element types immediately after the hovereditem
class
This means that in the style specified above, we want to apply the styles to the second adjacent item of the same class (i.e .item
). So if there are five adjacent div elements and I hover on the third element, the styles provided will affect the fifth element.
Check out this YouTube video below for a better understanding of how it works:
Top comments (12)
Video link broke
fixed
The article isn't totally accurate. The asterisk selector means to select any element; it has nothing to do with the parts of the selector that come before it.
Says find the element with class "item" and then select any adjacent element and then select any adjacent element to finally apply styles.
If you want to specifically target the same class, you need to write that class:
It doesn't matter much in the examples provided because they all are similar elements. But the distinction is important.
Agree. But it was a nice trick in the video example.
please read the article again and if possible try it on your own to understand it. Context matters. The video will give an even better understanding
I understand the selector fully. Your explanation about what is happening is incorrect.
in this case, wouldn't it be better and more future proof to specifically specify that we want to apply the effects to the .item classed elements adjacent to the hovered element as opposed to the adjacent element? Incase someone adds another div under every image or a p tag under every image etc. We wont be referencing the wrong elements.
Agreed
Good to know, thanks for the article!
This is something I will never use in my projects. I prefer more verbose but explicit selectors. This kind of syntax will throw any developer who is not familliar with it in a mind blowing void, like "WTF is that?!?" :D
well, at least you learnt something
That's great information thank you.
Absolute trick. Thanks