Home > Back-end >  Navbar active item color
Navbar active item color

Time:11-09

Is it possible to give color to an active item of the navbar in CSS without using JS and jQuery? Actually, I want my navbar working smooth.

  1. It is single page application.
  2. I tried .classname a.active(className of ){backgroundcolor: green;} but it only work with only with className active other remain in their position.

CodePudding user response:

Yes, you can do this without using JS, but you need to have some structure in your HTML to make it possible.

For example, in this snippet each li element starts with an input element of type radio. All the li input elements are given the same name so they are grouped - meaning when one radio button is clicked it is checked and all the others are unchecked. Using CSS we can select the immediately following element which has the text in it and change its background color, or any other required styling, if its preceding input element is checked.

.navbar-nav li {
  position: relative;
  display: inline-block;
}

.navbar-nav li input {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  opacity: 0;
  z-index: 1;
}

.navbar-nav li input:checked * {
  background: yellow;
}
<ul class="navbar-nav">
  <li><input type="radio" checked name="nav"><span>Item 1</span></li>
  <li><input type="radio" name="nav"><span>Item 2</span></li>
  <li><input type="radio" name="nav"><span>Item 3</span></li>
  <li><input type="radio" name="nav"><span>Item 4</span></li>
</ul>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Note that the input elements are given opacity 0 so they are still there but not visible, and they are made the same size and the same place as the item by being position absolute.

CodePudding user response:

Do you maybe mean either of those?

#nav li a:hover {
    color: red;
}

or

#nav li a:active {
    color: red;
}
  • Related