Reputation: 3735
I have a div
element and I want to show an image just below it when the user hovers over the div
. Through Javascript can do this with the mouseover
and mouseout
events but I want to do this using CSS
.
So how can I do it using CSS?
Upvotes: 1
Views: 839
Reputation: 907
You can do this with CSS:
<div class="outer">
Texty Texterson...
<div><img src="http://codinghorror.typepad.com/.a/6a0120a85dcdae970b0128776ff992970c-pi" /></div>
</div>
Css:
.outer div{
display: none;
}
.outer:hover div{
display: block;
}
But I will say doing this with jQuery/javascript enables you to do some nice effects like fade, etc.:
$(document).ready(function () {
$('.outer').hover(
function () {
$(this).find('div').fadeIn();
},
function () {
$(this).find('div').fadeOut();
});
});
Upvotes: 0
Reputation: 278
You can use CSS :after selectors for this effect.
#myDIV:hover:after
{
content: '';
display: block;
position: absolute;
}
from there you can style it as a regular element with your image as the background, or edit the content field to your liking. This will insert a pseudo element when you hover over #myDIV. If you need support for older browsers, you can look in to using your javascript code as a fallback, and use modernizr to detect browser capabilities.
Upvotes: 2
Reputation: 5153
You can do this with sibling selectors like +
or ~
: http://jsbin.com/uvepiq/1/edit
They will allow you to do a :hover
check on one element and apply styles to a following sibling element. So the image's normal style will be hidden with display: none
, and then when its preceding sibling is hovered, you can style it as display: block
or whatever.
Upvotes: 1