Display DIV when hovering another DIV's child CSS [duplicate]
Is it possible to display a DIV that's located outside the DIV's child?
<div id='container'>
<div>
<div>
<div id="one">Item 1</div>
<div id="two">Item 2</div>
<div id="three">Item 3</div>
</div>
</div>
<div class="extra" id="one-extra">Show item 1 extra info!</div>
<div class="extra" id="two-extra">Show item 2 extra info!</div>
<div class="extra" id="three-extra">Show item 3 extra info!</div>
</div>
Shouldn't class:hover class
do the job? Or is selecting DIV's outside its own DIV not possible without Javascript?
.extra {
display:none;
}
#one:hover #one-extra {
display: block;
}
Solution 1:
The issue is to do with your selector.
A CSS selector cannot traverse upwards. Specifically, the "#one-extra" has been defined as a "descendant". It's also possible to define "latter siblings" with the "~", "next siblings" with the "+", and "child" with a ">". See https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors for more information about CSS selectors.
Solution 1 - Changing the HTML
A change to your HTML and CSS could see styling apply with no need for JS:
<div id='container'>
<div id="one">Item 1</div>
<div id="two">Item 2</div>
<div id="three">Item 3</div>
<div class="contents">
<div class="extra" id="one-extra">Show item 1 extra info!</div>
<div class="extra" id="two-extra">Show item 2 extra info!</div>
<div class="extra" id="three-extra">Show item 3 extra info!</div>
</div>
</div>
and the CSS:
.extra {
display:none;
}
#one:hover ~ .contents #one-extra {
display: block;
}
Solution 2 - Add JS
The alternative is to use Javascript.
A JS library might be suitable, though I strongly suggest avoiding JQuery and other old libraries these days as they are bloated and provide nothing more than can be done with ease in raw Javascript, but add significant overhead, and add an unnecessary reliance.
If you're doing a lot of these things, specifically DOM manipulation, in JS in your project, a JS framework like Vue.js or React would provide a cleaner way to do this, though it would be a big change from no JS at all adding a large amount of bloat into your project.