0

I have a nav bar, and would like to set a default padding on each tab as being 14px wide, however for the first tab, which I will use as my logo, I wish to have a padding 18px wide. However when I tried to implement this, it did not work, and continued to use the 14px default.

#nav {
  text-decoration: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: black;
}

#nav>li {
  float: left;
  list-style-type: none;
}

#nav>li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

#logo {
  background-color: green;
  padding: 18px 16px;
}
<ul id="nav">
  <li><a href="/home" id="logo">Logo</a></li>
  <li><a href="/opt1">Opt1</a></li>
  <li><a href="/opt2">Opt2</a></li>
  <li><a href="/opt3">Opt3</a></li>
</ul>
j08691
  • 204,283
  • 31
  • 260
  • 272
tom894
  • 459
  • 1
  • 3
  • 14

4 Answers4

1

Just change #logo to #nav > li a#logo

Bouh
  • 1,303
  • 2
  • 10
  • 24
1

This has to do with CSS specificity

Instead of #logo, use nav > li a#logo

When you want to override a style, you need a more specific selector

Kwame Opare Asiedu
  • 2,110
  • 11
  • 13
1

It's because of CSS specificity: #nav > li a has a higher specificity then just #logo. This is why @Bouh's answer works. I would read up on it.

Here's a specificity calculator: https://specificity.keegan.st/

Alternatively, you can avoid specificity issues by avoiding overuse of ids and child selectors, for example:

.navlist {
  text-decoration: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: black;
}

.navlist-item {
  float: left;
  list-style-type: none;
}

.navlink {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

.logo {
  background-color: green;
  padding: 18px 16px;
}
<ul class="navlist" id="nav">
  <li class="navlist-item"><a class="navlink logo" href="/home" id="logo">Logo</a></li>
  <li class="navlist-item"><a class="navlink" href="/opt1">Opt1</a></li>
  <li class="navlist-item"><a class="navlink" href="/opt2">Opt2</a></li>
  <li class="navlist-item"><a class="navlink" href="/opt3">Opt3</a></li>
</ul>


    
DanCouper
  • 850
  • 6
  • 15
0

The problem is CSS selector specificity.

#nav > li a

is more specific than:

#logo

so the first example here will always win for the HTML you've provided (regardless of order in the CSS file)

Here is an updated set of CSS rules:

#nav {
    text-decoration: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: black;
}

#nav > li {
    float: left;
    list-style-type: none;
}

#nav > li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

##nav > li a#logo { /* this selector has been changed to be more specific */
    background-color: green;
    padding: 18px 16px;
}
Adrian Roworth
  • 813
  • 1
  • 7
  • 16