0

Well, that should be quite simple. I have the following CSS snippet:

.nav-item > .nav-link:not(.active)::after {
  content: "test";
  display: block;
  width: 0;
  border-bottom: solid 2px #019fb6;
  transition: width .3s;
}

However, I'd like to do something like that:

.nav-item::after > .nav-link:not(.active) {
  content: "test";
  display: block;
  width: 0;
  border-bottom: solid 2px #019fb6;
  transition: width .3s;
}

And finally:

.nav-item:hover::after > .nav-link:not(.active) {
  width: 100%;
}

I'm trying to create a hover effect that only works on nav-items that doesn't have the "active" class. But, that ins't working. What am I doing wrong?

Html:

<li class="nav-item"><a class="nav-link text-left" href="#">Second Item</a></li>
<li class="nav-item"><a class="nav-link text-left active" href="#">FirstItem</a></li>

Thanks in advance.

gusta
  • 69
  • 7
  • Does this answer your question? [Is there a CSS parent selector?](https://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector) – disinfor Jun 27 '21 at 23:33

1 Answers1

1

The main issue is that, at the time of your post, CSS doesn't allow you to go up. It seems you're trying to detect an active class at the nested <a> level and apply something to the pseudo content of <a>'s parent element. Instead, move the active class to the parent (li) level. Then you can control the pseudo content. Note that I added overflow: hidden to the un-hovered state, so that the content was not visible. In addition, I added opacity to the transition to make it a little smoother looking.

.nav-item:not(.active)::after {
  content: "test";
  display: block;
  width: 0;
  opacity: 0;
  border-bottom: solid 2px #019fb6;
  transition: width 0.3s, opacity 0.3s;
  overflow: hidden;
}

.nav-item:not(.active):hover::after {
  width: 100%;
  opacity: 1;
}
<ul>
  <li class="nav-item active"> <!-- active moved here -->
    <a class="nav-link text-left" href="#">FirstItem</a></li>
  <li class="nav-item">
    <a class="nav-link text-left" href="#">Second Item (active)</a></li>
</ul>
Andy Hoffman
  • 18,436
  • 4
  • 42
  • 61
  • That solved my problem. Great explanation by the way. You cleared my mind. Thanks. – gusta Jun 28 '21 at 01:37
  • @gusta Have a look at [this](https://developer.mozilla.org/en-US/docs/Web/CSS/:has)—the `:has` pseudo-class selector—which will hopefully gain support one day and render my answer obsolete. – Andy Hoffman Jun 28 '21 at 02:15