I came across an example of revealing a hidden div which is inside an element using css only
<style type="text/css">
#shopCart:hover .shopCartDetail {
display: block;
}
</style>
<div id="shopCart">
Shop Cart
<div class="shopCartDetail"><style>.shopCartDetail {display:none}</style>
This is Shop Cart Detail</div>
</div>
Working example here http://jsfiddle.net/7DRTD/
In my scenario, the style display:none is created by jQuery. Revealing the hidden div using hover does not work: http://jsfiddle.net/Z2mtF/
What can be the issue here? The html code looks same, both examples add inline style to the div.
The question is: why does the second scenario not work?
Thank you.
In a general sense, styles applied directly to an individual element take precedence over settings from the stylesheet. This is (part of) the “cascading” effect that is the “C” in “CSS”. So when you hide the element with jQuery with the following in your document ready:
…it is equivalent to adding
style="display:none"directly to the element, which has the same “problem”: http://jsfiddle.net/Z2mtF/2/This is not the same as applying a class to the element, which is what your “emulation” above was doing with the
<style>element inside the<div>.So the hover rule isn’t important enough to take effect. One way to fix this is to make the hover rule important:
Demo: http://jsfiddle.net/Z2mtF/1/
Settings in the stylesheet marked as
!importantwill take precedence over the inline style attributes.Note that it’s tidier if you use
.show()and.hide()instead of explicitly setting thedisplayproperty via the.css()method.