raold raold - 4 months ago 14
CSS Question

CSS - How to hide div by hovering another div

Hi I have a problem with some css code. I created simple jsfiddle, so I hope you will understand my problem.

Example:

jsfiddle.net

<div id="main">
<div id="one">
<p>Hover to hide div below</p>
</div>
<div id="two">
<p>hide me please</p>
</div>
</div>
<div id="main">
<div id="one">
<p>Hover to hide div below (this works)</p>
<div id="two">
<p>hide me please</p>
</div>
</div>

</div>


CSS

#one{
background-color:green;
color:white;
height:40px;
}
#two{
background-color:red;
color:white;
height:40px;
display:in-line;
}
/* Help please */
#one:hover > #two {
display:none;
}
#main #one:hover > #main #two {
display:none;
}


Thank you and if someone can edit my post and make better title I will be grateful. My English is weak.

Answer

First you should use class instead of id in your code. You can use + selector to hide next sibling element.

  1. For first .main div you can use .main div:hover + .two to hide .two when you hover over .one
  2. For second .main div you can use main div p:first-child:hover + .two to hide .two when you hover over first p in .main or you can just use .main div > .two

.one {
  background-color: green;
  color: white;
  height: 40px;
}
.two {
  background-color: red;
  color: white;
  height: 40px;
  display: in-line;
}
.main div:hover + .two,
.main div p:first-child:hover + .two {
  display: none;
}
<div class="main">
  <div class="one">
    <p>Hover to hide div below</p>
  </div>
  <div class="two">
    <p>hide me please</p>
  </div>
</div>
<div class="main">
  <div class="one">
    <p>Hover to hide div below (this works)</p>
    <div class="two">
      <p>hide me please</p>
    </div>
  </div>
</div>