Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide element on hover of another element

Tags:

html

css

I know it can be done in JavaScript, however I am looking for solution in CSS.

I have three divs.

  • div#hide should be visible by default, #show should be hidden.
  • When I hover on #main, #hide should hide and #show should be visible.

div#show works fine but #hide doesn't hide when #main is hovered. How can we do it in css?

#show {
  display: none
}
#main:hover + #show {
  display: block
}
#main:hover + #hide {
  display: none
}
<div id="main">
  Hover me
</div>
<div id="show">
  Show me on hover
</div>
<div id="hide">
  Hide me on hover
</div>
like image 456
Imad Avatar asked Jan 23 '17 09:01

Imad


People also ask

How do I make hover affect another element?

If you have two elements in your HTML and you want to :hover over one and target a style change in the other the two elements must be directly related--parents, children or siblings. This means that the two elements either must be one inside the other or must both be contained within the same larger element.

How do I hide a div inside another div?

What you need to do is set the overflow property on the parent to be hidden. By default, your browser will set it to visible, which makes it so that anything that sticks out the sides of your element will be shown, as you've seen. Here's some code that shows overflow: hidden at work.

How do I hide a div until hover?

You can do this by using the :hover property of a page element. For example, if we have a div inside another div, we can check the hover of the outer div to show/hide the inner div. This CSS hides the inner div by default using "display: none;".


1 Answers

Instead of + you want to use ~ combinator for hide element because + selects only next-sibling

#show {
  display: none
}
#main:hover + #show {
  display: block
}
#main:hover ~ #hide {
  display: none
}
<div id="main">
  Hover me
</div>
<div id="show">
  Show me on hover
</div>
<div id="hide">
  Hide me on hover
</div>
like image 168
Nenad Vracar Avatar answered Oct 30 '22 12:10

Nenad Vracar