Question

I have a parent div in my code, and 2 child divs. I want that on hovering the first child, the second child to hide. I want to do that only with css or js.

Here's my Fiddle

<div class="parrent">
    <div id="child1">
        Hide child2
    </div>

    <div id="child2">  
        I must hide
    </div>
</div>

Thank you!

Was it helpful?

Solution

Use this:

#child1:hover ~ #child2 {
    visibility:hidden;
}

Demo

This uses the General sibling combinator ~

~ selector: The general sibling combinator selector is very similar to the adjacent sibling combinator selector we just looked at. The difference is that that the element being selected doesn't need immediately succeed the first element, but can appear anywhere after it.


You can also use the Adjacent sibling combinator +, depending on the rest of your code.

+ selector: An adjacent sibling combinator selector allows you to select an element that is directly after another specific element.

#child1:hover + #child2 {
    visibility:hidden;
}

Demo

OTHER TIPS

#child1:hover #child2 {
    visibility:hidden;
}

This will not work as now you're saying that #child2 must be a child of #child1.

What you can do is this:

$(document).ready(function(){
    $('#child1').hover(function(){
        $('#child2').hide();
    }, function(){
        $('#child2').show();
    });
});

Or use the CSS code:

#child1:hover ~ #child2 {
    visibility:hidden;
}

You can use below jquery code:

$(document).ready(function(){
    $('#child1').on('mouseover',function(){
        $("#child2").hide();
    }).on('mouseout',function(){
        $("#child2").show();
    });
});

Before doing this you should know how to refer to a sibling element of an element in CSS.

instead of the following syntax-

#child1:hover #child2

You need the following:

#child1:hover+#child2

Fiddle demo

N.B. Basically + is for a reference to a sibling

Reference

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top