Thor The dog
Thor The dog

Reputation: 55

Change colour of all elements expect the hovered element using CSS

I am creating a list using HTML and CSS. What I am trying to achieve is all the elements will be black until they are hovered on. When hovered, all elements except the hovered text will change color. I am attaching my code; it would be helpful if anyone could point out the mistake or tell me why it's not working.

.sub-menu-mast {
  line-height: 30px;
  background-color: rgb(254, 254, 254);
  width: 9rem;
  cursor: pointer;
}

.sub-menu-mast>li>a {
  color: black;
  position: relative;
  left: 10%;
}

.sub-menu-mast a:not(:hover) {
  color: red;
}
<nav>
  <ul>
    <li>
      <a>XYZ </a>
      <ul class="sub-menu-mast">
        <li><a href="">Track</a></li>
        <li><a href="">Return</a></li>
      </ul>
    </li>
  </ul>
</nav>

Upvotes: 0

Views: 84

Answers (1)

F. M&#252;ller
F. M&#252;ller

Reputation: 4062

Not sure, if I understood your request. Do you mean something like this?

.sub-menu-mast {
  line-height: 30px;
  background-color: rgb(254, 254, 254);
  width: 9rem;
  cursor: pointer;
}

.nav,
.menu,
.sub-menu-mast {
  outline: 1px dashed teal;
}

.sub-menu-mast>li>a {
  color: black;
  position: relative;
  left: 10%;
}

.sub-menu-mast li a {
  outline: 1px dashed red;
}

.sub-menu-mast:hover a:not(a:hover) {
  color: red;
}

* {
  box-sizing: border-box;
}

.my-nav {
  width: fit-content;
  display: flex;
  flex-flow: row nowrap;
  outline: 1px dashed teal;
}

.my-nav ul {
  padding: 0;
  margin: 0;
}

.my-nav li {
  width: 100%;
}

.my-nav a {
  color: black;
  display: block;
  padding: 5px;
  border-bottom: 1px solid black;
}

.my-sub-menu li a {
  padding-left: 2em;
}

.my-nav li:hover,
.my-sub-menu li:hover {
  background: wheat;
}


/* either this ... */

.my-sub-menu:hover li a:not(:hover) {
  color: red;
}


/* ... or that */


/*
.my-sub-menu:hover li a {
  color: red;
}

.my-sub-menu:hover li a:hover {
  color: black;
}*/
<nav class="nav">
  <ul class="menu">
    <li>
      <a>XYZ </a>
      <ul class="sub-menu-mast">
        <li><a href="">Track</a></li>
        <li><a href="">Return</a></li>
        <li><a href="">More</a></li>
        <li><a href="">Fixed</a></li>
      </ul>
    </li>
  </ul>
</nav>

<nav class="my-nav">
  <ul class="my-menu">
    <li><a href="#">Item A</a></li>
    <ul class="my-sub-menu">
      <li><a href="#">Item 1</a></li>
      <li><a href="#">Item 2</a></li>
      <li><a href="#">Item 3</a></li>
    </ul>
  </ul>
</nav>

Upvotes: 2

Related Questions