Search code examples
csshtmlparentmouseoverhighlighting

highlight div1 and div2 on div2 mousover, highlight nothing on div1 mouseover


Div highlighting question

I have 2 divs stacked on top of each other inside a container. Here is the behavior I want: when you mouseover the top div, nothing happens. when you mouse over the bottom div, the top div background changes color, and the bottom div's background changes a different color. In the sample code I tried, mousing over the container div makes the top turn green and the bottom turn vlueviolet. I want a mouseover on the bottom to cause this behavior, but I want a mouseover on the top to do nothing. I feel like I could get this done in jQuery using a parent selector or something, but it seems like I should be able to do this in pure CSS. Thanks!

Here is what I've tried, which of course doesn't work, but gives an idea of what I'm trying to do.

<html>
<head>
<style>
div
{
display:inline;
border:1px dotted black;
font-family:Courier;
background:white;
}
div#outer{
display:inline-block;
border:2px solid red;
}
div#outer:hover #top{
background:green;
}
div#outer:hover #bottom{
background:blueviolet;
}
div#top:hover, div#bottom:hover{
background:white;
}
</style>
</head>
<body>
<div id=outer>
<div id=top>
&nbsp; &nbsp;top
</div>
<br>
<div id=bottom>
bottom
</div>
</div>
</body>
</html>

Solution

  • I changed up your CSS a little bit. Basically to make it bigger.

    The order is important here.

    This is not perfect due to the outer div's border.

    <style>
    div {
        border:1px dotted black;
        font-family:Courier;
        background:white;
    }
    
    div#top, div#bottom {
        height: 200px;
        width: 200px;
    }
    
    div#outer:hover #bottom:hover {
        background:blueviolet;
    }
    
    div#outer:hover #top {
        background:green;
    }
    
    div#outer #top:hover{
        background:white;
    }
    
    div#outer{
        display:inline-block;
        border:2px solid red;
    }
    </style>