Amit Verma
Amit Verma

Reputation: 41219

How to change the background color of Active links in a menu bar?

I copied the following code from w3schools.com and added it to all pages on my website. Navigation is working fine, but Background color of active links in the menu doesn't change.

How can I fix this?

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
}
li {
  float: left;
}
a:link,
a:visited {
  display: block;
  width: 120px;
  font-weight: bold;
  color: #FFFFFF;
  background-color: #98bf21;
  text-align: center;
  padding: 4px;
  text-decoration: none;
  text-transform: uppercase;
}
a:hover,
a:active {
  background-color: #7A991A;
}
<ul>
  <li>
    <a href="/home.php">Home</a>
  </li>

  <li>
    <a href="/news.php">News</a>
  </li>
  <li>
    <a href="/contact.php">Contact</a>
  </li>
  <li>
    <a href="/about.php">About</a>
  </li>
</ul>

Upvotes: 0

Views: 97

Answers (1)

Pugazh
Pugazh

Reputation: 9561

You would need to add a CSS class on the active page. Here i added class="active"

Change CSS as below

a:hover,
a:active,
a.active {
  background-color: #7A991A;
}

On home.php change the navigation code as below.

<ul>
  <li>
    <a href="/home.php" class="active">Home</a>
  </li>

  <li>
    <a href="/news.php">News</a>
  </li>
  <li>
    <a href="/contact.php">Contact</a>
  </li>
  <li>
    <a href="/about.php">About</a>
  </li>
</ul>

On news.php make the change as below, Similarly for other pages

<ul>
  <li>
    <a href="/home.php">Home</a>
  </li>

  <li>
    <a href="/news.php" class="active">News</a>
  </li>
  <li>
    <a href="/contact.php">Contact</a>
  </li>
  <li>
    <a href="/about.php">About</a>
  </li>
</ul>

Upvotes: 1

Related Questions