So is it possible to make this work
#element img:hover #otherelement {...}
like
#element:hover #otherelement {...}
Yes it is, try:
#element:hover + #otherelement {...}
or
#element:hover ~ #otherelement {...}
As img
cannot hold any other nested tag, I assume you are targeting the adjacent element, you can use adjacent selector here using +
#element img: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 >
What your first selector is looking for is something called #otherelement
inside 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
.
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.
What you can do is selecting next element(s) by:
element1 + element2 Selects every element2
element that are placed immediately after element1
element(s). They're siblings.
#element img:hover + #otherelement
If the #otherelement
is placed right after img
, it'll be selected when img
is hovered.
Another option is:
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
.
#element img:hover ~ #otherelement
If #otherelement
and img
are siblings, and #otherelement
is placed somewhere after the img
, it'll be selected when img
is hovered.
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;
}