I’ve been trying to figure out on how to set the current page I’m at to a different background color than the other links, but to no avail.
HTML
<div id="navigation">
<ul>
<li><a href="<?php echo base_url() ?>index.php/home">Home</a></li>
<li><a href="<?php echo base_url() ?>index.php/portfolio">Portfolio</a></li>
<li><a href="<?php echo base_url() ?>index.php/about">About</a></li>
<li><a href="<?php echo base_url() ?>index.php/gallery">Gallery</a></li>
<li><a href="<?php echo base_url() ?>index.php/blog">Blog</a></li>
</ul>
</div>
What I want is to set the current active link to black, and the other four links to grey. That way if I visit Portfolio, for example, that link is black and the rest are grey. How would I do this?
Thankfully, there is no Javascript involved. HTML and CSS will work fine for this task. First off, let’s create your HTML. You obviously know what page you are on, so we are going to add a class to the current page’s link. So, for example, if we were on
/index.php/homeour markup might look similar to this.Now, before we color the current link we are going to color the rest of the links. We can select the rest of the links via CSS like so.
The following CSS will select all
<a>elements that are children of thenavigationelement. So now we need to set its background color. The CSS property for setting the background color isbackground-color: xxx. Wherexxxis either the hex code, rgb value, or the name of the color. So we would do the following to have all the links grey.This will set every link to the color grey. Now, we need to set the current link to the color black.
If you noticed, we added
class="current"to the current link, the home link in this case. Next we need to create the appropriate styling for this. Our CSS declaration will look similar to this.The above declaration applies to all elements with the class
currentthat is a child of the elementnavigation. And so now we set the background color like so.So, our final CSS would look like so.
Note that the order is important! If we were to put the second declaration first, it would be overridden by the, more general, link declaration.