Can I use img: hover to get another element?

So what can this job do

#element img:hover #otherelement {...} 

as

 #element:hover #otherelement {...} 

it is important that img remains specified, because the images are automatic in what I am doing.

+1
source share
5 answers

What you can do is select the following item (s):

Combined Adjacent Brother

element1 + element2 Selects each element2 element, which is placed immediately after element1 elements. They are brothers and sisters.

 #element img:hover + #otherelement 

If #otherelement placed immediately after img , it will be selected when img is visible.

Another variant:

General Meeting Combinator

element1 ~ element2 Corresponds to the occurrences of element2 preceded by element1 , while they have the same parent. They are also siblings, but element2 does not have to precede element1 .

 #element img:hover ~ #otherelement 

If #otherelement and img are siblings, and #otherelement is placed somewhere after img , it will be selected when img is hovering.

Here is an example

HTML

 <div id="parent"> <img src="http://lorempixel.com/200/200/" alt="Sport"> <div class="text">This is a text.</div> </div> 

CSS

 #parent { overflow: hidden; width: 200px; height: 200px; } .text { position: relative; -webkit-transition: .3s all; -moz-transition: .3s all; transition: .3s all; background-color: rgba(255,255,255,.5); height: 40px; line-height: 40px; } #parent img:hover + .text { top: -40px; } 
+2
source

Since img cannot hold any other nested tag, I assume that you are targeting a neighboring element, you can use the adjacent selector here using +

 #element img:hover + #otherelement {...} 

The selector above will select the item next to the img tag when the image freezes.

Note. Above selector will only work if you have markup like

 <div id="element"> <img src="#" /> <div id="otherelement"></div > </div > 

But it won’t succeed if you have markup like

 <div id="element"> <img src="#" /> </div > <div id="otherelement"></div > 
+4
source

What your first selector is looking for is called #otherelement inside the image. Images cannot have children.

If the element is a child of the image, you can try img:hover~#otherelement or img:hover+#otherelement .

+1
source

Yes, try:

 #element:hover + #otherelement {...} 

or

 #element:hover ~ #otherelement {...} 
0
source

You can use the: hover pseudo-class for any element. There are cross-browser considerations. You can use polyfill as Selectivizr for this.

As for your question, you might consider targeting a common ancestor for both elements that you are trying to customize using hover, and apply your styles this way.

0
source

Source: https://habr.com/ru/post/1497309/


All Articles