skip to Main Content

I want the first item in a list in my navigation to stay underlined, and the rest to underline on hover, with the first item only not underlining until I hover on another list item. I have already tried the first child selector to try ad it but it does not seem to work.

.nav__links a {
  padding-block: 5px;
  color: var(--text-dark);
  border-bottom: 3px solid transparent;
}

.nav__links a:hover {
  border-color: var(--btn-primary-color);
}
<ul class="nav__links" id="nav-links">
  <li><a href="#home">HOME</a></li>
  <li><a href="#company">COMPANY</a></li>
  <li><a href="#services">SERVICES</a></li>
  <li><a href="#contact">CONTACT</a></li>
  <li class="nav__links__btn nav__remove__btn">
    <button class="btn">CONTACT US</button>
  </li>
  <li class="nav__links__btn nav__remove__btn">
    <button class="btn">GET A FREE QUOTE</button>
  </li>
</ul>

I have already tried the child selector on the first li item but had no luck. I’m a bit unsure of how to approach it.

.nav__links a {
        padding-block: 5px;
        color: var(--text-dark);
        border-bottom: 3px solid transparent;
    }

    .nav__links a:hover {
        border-color: var(--btn-primary-color);
    }

2

Answers


  1. .nav__links:first-of-type a {
        /* css for First anchor */
    }
    .nav__links:hover a {
        /* css for hovered anchor */
    }
    
    Login or Signup to reply.
  2. As below.

    The first child and any hovered item gets the border.

    If the first child has any sibling that is hovered, its border is removed.

    ul {
      list-style:none;
      display: flex;
    }
    
    li {
      background: lightblue;
      margin-right: .25em;
      padding: .25em;
      border-bottom: 5px solid transparent;
      transition: border-color .2s ease;
    }
    
    a {
     text-decoration:none;
      display: block;
    }
    
    li:first-child, 
    li:hover {
      border-bottom: 5px solid blue;
    }
    
    li:first-child:has( ~ li:hover) {
      border-bottom-color: transparent;
    }
    <ul>
      <li><a href="">List Item 1</a></li>
      <li><a href="">List Item 2</a></li>
      <li><a href="">List Item 3</a></li>
      <li><a href="">List Item 4</a></li>
      <li><a href="">List Item 5</a></li>
    </ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search