1

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?

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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();
    });
});

1 Comment

What @KyleSomogyi said if using CSS :after. If using jquery use .next('img') or whatever your element is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.