Home > Blockchain >  add background color for active clicked item in nav css
add background color for active clicked item in nav css

Time:12-11

I try all solutions but still this not work for me.

.nav-home > a:active {
    background: #4a90e2;
}
.nav-navigation > a:active {
    color: #fff !important;
     background: #4a90e2;
}
<aside  style="background-color: #FFF;">
        <section >
            <ul  data-widget="tree">
                <li >Navigation</li>
                <li >
                    <a href="#">
                        <i ></i> <span>Home</span>
                    </a>
                </li>
                </ul>
                </section>
                
</aside>

In above example this working only during click nav then you see blue background, but I need display always blue color when this tab is clicked.

CodePudding user response:

You should use JavaScript to save the state of the currently clicked tab:

document.querySelector('.nav-home > a').addEventListener('click', () => {
    document.querySelector('.nav-home > a').style.backgroundColor = '#4a90e2';
})
.nav-home > a:active {
    background: #4a90e2;
}
.nav-navigation > a:active {
    color: #fff !important;
     background: #4a90e2;
}
<aside  style="background-color: #FFF;">
        <section >
            <ul  data-widget="tree">
                <li >Navigation</li>
                <li >
                    <a href="#">
                        <i ></i> <span>Home</span>
                    </a>
                </li>
                </ul>
                </section>
                
</aside>

CodePudding user response:

I assume that you want to change active tab background, so you can add class active to current clicked tab and remove from others

here is what I did :

const handleActiveTab = (element)=>{

  Array.from(document.querySelectorAll('a')).forEach((el) => el.classList.remove('active'));


 element.classList.add('active')
}
.nav-home > a:active {
    background: #4a90e2;
}
.nav-navigation > a:active {
    color: #fff !important;
     background: #4a90e2;
}

.active{
  background-color:#4a90e2 !important;
}
<aside  style="background-color: #FFF;">
        <section >
            <ul  data-widget="tree">
                <li >Navigation</li>
                <li >
                    <a href="#" onclick="handleActiveTab(this)">
                        <i ></i> <span>Home</span>
                    </a>
                    <br/>
                    <a href="#" onclick="handleActiveTab(this)">
                        <i ></i> <span>about-us</span>
                    </a>
                      <br/>
                    <a href="#" onclick="handleActiveTab(this)">
                        <i ></i> <span>contact-us</span>
                    </a>
                </li>
                </ul>
                </section>
                
</aside>

  • Related