Home > Enterprise >  How to get rid of right margin in last item of navigation bar using last child
How to get rid of right margin in last item of navigation bar using last child

Time:06-03

I have created a navigation bar and have added margin-right to all the items.

However, when I try to get rid of the margin right in the last child of the navigation item "contact", it won't disappear.

.navbar {
  text-decoration: none;
  margin-bottom: 150px;
}

.nav-item {
  display: inline-block;
  text-decoration: none;
}

.nav-list {
  text-align: center;
}

.nav-list li a {
  text-decoration: none;
  margin-right: 100px;
}

.nav-list ul li a:last-child {
  margin-right: 0;
}

.nav-list li a:active {
  color: #000;
}

.nav-list li a:visited {
  color: #000;
}
<div>
  <nav >
    <ul >
      <li ><a href="#home">Home</li></a>
        <li ><a href="#about">About</li></a>
          <li ><a href="#work">Work</li></a>
            <li ><a href="#services">Services</li></a>
              <li ><a href="#contact">Contact</li></a>
    </ul>
  </nav>
</div>

Here is my code pen: https://codepen.io/derrickogole/pen/rNxbaaK

Is there a way to do this without adding an additional class to contact?

CodePudding user response:

Use the :last-child psuedo-class.

.nav-item:last-child a {
  margin: 0;
}

See it here:

.navbar {
  text-decoration: none;
  margin-bottom: 150px;
}

.nav-item {
  display: inline-block;
  text-decoration: none;
}

.nav-list {
  text-align: center;
}

.nav-list li a {
  text-decoration: none;
  margin-right: 100px;
}

.nav-list ul li a:last-child {
  margin-right: 0;
}

.nav-list li a:active {
  color: #000;
}

.nav-list li a:visited {
  color: #000;
}

.nav-item:last-child a {
  margin: 0;
}
<div>
  <nav >
    <ul >
      <li ><a href="#home">Home</a></li>
      <li ><a href="#about">About</a></li>
      <li ><a href="#work">Work</a></li>
      <li ><a href="#services">Services</a></li>
      <li ><a href="#contact">Contact</a></li>
    </ul>
  </nav>
</div>

Additionally, your markup was invalid due to closing </li> before </a>. a is nested in li so it needs to be closed first.

  • Related