Management of Active/Inactive Items in the mini-learn HTML Navbar

html navbar active inactive buttons management
10 November 2024

One of the most common challenges that web developers face is how to manage active and inactive items in a navbar without unnecessary code repetition. Note that the concept of DRY (Don't Repeat Yourself) is very important in programming, but sometimes we need to find ways to implement it quickly and with few changes, leading to a desirable outcome.

Assume you have a simple navbar and want to manage its current (active) and inactive items. In this case, instead of using complex methods or adding frameworks, we can achieve this with a simple technique that at least requires no repetition.

First, you need to design the HTML page. To create the navbar, use the ul and li tags. Then, with CSS, we can manage the active and inactive states.

Keep in mind that we need to write code that allows management and the ability to easily add it to any other page or document. This is the goal of this example.

HTML and CSS Code


<ul class="navbar">
    <li class="nav-item active">Home</li>
    <li class="nav-item">About</li>
    <li class="nav-item">Services</li>
    <li class="nav-item">Contact</li>
</ul>

<style>
    .navbar {
        list-style-type: none;
        margin: 0;
        padding: 0;
        overflow: hidden;
        background-color: #333;
    }

    .nav-item {
        float: left;
        display: block;
        color: #f2f2f2;
        text-align: center;
        padding: 14px 16px;
        text-decoration: none;
    }

    .nav-item:hover {
        background-color: #ddd;
        color: black;
    }

    .active {
        background-color: #04AA6D;
    }
</style>

Line-by-Line Code Explanation

  • <ul class="navbar"> - Creates an unordered list without numbering that represents the navbar.
  • <li> - Specifies the items in the navbar.
  • class="nav-item active" - CSS classes to manage the visual state of the item, where active indicates that this item is currently active.
  • .navbar - The main style for the navbar, like background and positioning.
  • .nav-item - Basic styles for each navbar item, including color and font size.
  • .nav-item:hover - Defines the hover state which changes the background color when the mouse hovers over the item.
  • .active - A specific style for the active item, defined by changing its background color.

FAQ

?

How can I activate an inactive item?

?

Is it possible to change the active state automatically?