Can I Use Img:hover To Get Another Element?
Solution 1:
As img cannot hold any other nested tag, I assume you are targeting the adjacent element, you can use adjacent selector here using +
#elementimg:hover + #otherelement {...}
The above selector will select the element next to img tag when the image is hovered.
Note: Above selector will work only if you've your markup like
<div id="element">
<img src="#" />
<div id="otherelement"></div >
</div >
But will fail if you've markup like
<div id="element">
<img src="#" />
</div >
<div id="otherelement"></div >
Solution 2:
What you can do is selecting next element(s) by:
Adjacent sibling combinator
element1 + element2 Selects every element2 element that are placed immediately after element1 element(s). They're siblings.
#elementimg:hover + #otherelementIf the #otherelement is placed right after img, it'll be selected when img is hovered.
Another option is:
General sibling combinator
element1 ~ element2 Matches occurrences of element2 that are preceded by element1 while they have the same parent. They're siblings too, but element2 doesn't have to be immediately preceded by element1.
#elementimg:hover ~ #otherelementIf #otherelement and img are siblings, and #otherelement is placed somewhere after the img, it'll be selected when img is hovered.
HTML
<divid="parent"><imgsrc="http://lorempixel.com/200/200/"alt="Sport"><divclass="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;
}
#parentimg:hover + .text {
top: -40px;
}
Solution 3:
What your first selector is looking for is something called #otherelementinside an image. Images can't have child elements.
If the element is a sibling of the image, you might want to try img:hover~#otherelement or img:hover+#otherelement.
Solution 4:
Yes it is, try:
#element:hover + #otherelement {...}
or
#element:hover ~ #otherelement {...}
Solution 5:
You can use the :hover pseudo class on any element. There are considerations to be made in regards to cross-browser. You can use a polyfill like Selectivizr for that, though.
As for your question, you might want to consider targeting a shared ancestor for both elements you are trying to target with the hover and apply your styles that way.
Post a Comment for "Can I Use Img:hover To Get Another Element?"