Saif Obeidat
Saif Obeidat

Reputation: 148

CSS hover does not affect on other element

CSS :hover works when I use it for it's own element, but when i tried to affect another element, it had no effect.

For example, when I hover this button, the hidden links should appear, but they do not.

.dropdown {
  position: relative;
  display: inline-block;
  border: 1px solid black;
  width: 200px;
}
.dropbutton {
  width: 100%;
  height: 60px;
  color: white;
  background: #017678;
  border: none;
}
.dropcontent a {
  color: black;
  text-align: center;
  line-height: 40px;
  text-decoration: none;
  height: 40px;
  background-color: #DDD;
  border-width: 0 0 1px 0;
  border-style: solid;
  border-color: #9fa0a8;
  display: none;
}
a:last-of-type {
  border: none;
}
.dropbutton:hover .dropcontent {
  display: block;
}
<div class="dropdown">
  <button class="dropbutton">SHOW CONTENT</button>
  <div class="dropcontent">
    <a href="#">c1</a>
    <a href="#">c2</a>
    <a href="#">c3</a>
  </div>
</div>

Upvotes: 1

Views: 1473

Answers (3)

I'd move the display: none; to the .dropcontent itself - as it now pertains to its anchors, that is, links, and as such, neither current answer would work -, then use

.dropbutton:hover + .dropcontent
{
    display: block;
}

But you must not add anything between dropbutton and dropcontent afterwards, or it will not work any more.

Upvotes: -1

Good Idea
Good Idea

Reputation: 2821

Are you using Javascript to do this?

var button = document.getElementsByClassName('.dropbutton')[0],
    menuContent = docuemnt.getElementsByClassName('.dropcontent')[0];

button.onmouseover = function(event) {
    menuContent.style.display['block'];
}
button.onmouseout = function(event) {
    menuContent.style.display['none'];
}

With a slight change to your CSS: .dropbutton should have display: none, and you should remove the display: none from .dropcontent a

Upvotes: -1

Quentin
Quentin

Reputation: 943569

A space is a descendant combinator. It targets descendants, but the div is not a descendant of the button, it is a sibling.

You need to use the adjacent sibling combinator instead: a plus sign.

You also need to target the links (which are descendants of .dropcontent so you should use a descendant combinator there) since it is those which you have set display: none on and not the div.

.dropbutton:hover + .dropcontent a {

Upvotes: 8

Related Questions