M. El-Set
M. El-Set

Reputation: 763

Show div when hover another div using only css

I have searched the web for this one but didn't find anything similar.

Say we have div A and div B. When hover on div A, div b should be visible ON (should look like overwriting) div A and not placed under.

It should appear like only the content of div A has changed to content of div B.

How can this be done in pure CSS and HTML?

#container > div {
    display: none
}
#container > div:first-child {
    display: block
}
#container > div:hover + div {
    display: block

<div id="container">
    <div>A</div>
    <div>B</div>
</div>

Upvotes: 22

Views: 106061

Answers (4)

Rehan
Rehan

Reputation: 1

It works; you can try nested css like:

HTML

<div class="a">
    <div class="b">
    </div>
</div>

CSS

.a:hover{
  .b{
     /* properties of hover */
   }
}

Upvotes: -1

algorhythm
algorhythm

Reputation: 8728

If you don't want to use the selector + or ~ which aren't compatible with some browsers, it is just possible if the <div /> to show (e.g. div#b) is a child of the <div /> to hover (e.g. div#a).

<div id="a">
    <div id="b"></div>
</div>

<style>
    div#b {
        display: none;
    }

    div#a:hover div#b {
        display: block;
    }
</style>

Upvotes: 15

Prakash
Prakash

Reputation: 31

Its works, but your css should be like this

<style>
#b{display:none;}
div#a:hover div#b{display:inline}
</style>

Upvotes: 3

PassKit
PassKit

Reputation: 12581

This will work, but only if the two divs are adjacent and b follows a.

#a:hover + #b {
    background: #f00
}

<div id="a">Div A</div>
<div id="b">Div B</div>

If you have divs in between use ~

#a:hover ~ #b {
    background: #f00
}

<div id="a">Div A</div>
<div id="c">Div C</div>
<div id="b">Div B</div>

To go the other way around, unfortunately you will need Javascript

// Pure Javascript
document.getElementById('b').onmouseover = function(){
    document.getElementById('a').style.backgroundColor = '#f00';
}
document.getElementById('b').onmouseout = function(){
    document.getElementById('a').style.backgroundColor = '';
}

// jQuery
$('#b').hover(
  function(){$('#a').css('background', '#F00')}, 
  function(){$('#a').css('background', '')}
);

Full fiddle http://jsfiddle.net/p7hLL/5/

Upvotes: 31

Related Questions