简体   繁体   中英

How to change background color of active nav-link?

I have a darkmode version of my asp.net site and everything works except the active card-header tab. Ive tried a bunch of different CSS to figure it out but i cant get it.

I thought something like this would work

.nav-link > .active {
    background-color: var(--bg);
    color: var(--color-text);
}

But it does not. Here is the code below:

<div class="row">
    <div class="col-md-6 offset-md-3">
        <div class="card login-logout-tab">
            <div class="card-header">
                <ul class="nav nav-tabs card-header-tabs">
                    <li class="nav-item">
                        <a class="nav-link" href="/Identity/Account/Login">Sign In</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/Identity/Account/Register">Sign up</a>
                    </li>
                </ul>
            </div>
            <div class="card-content">
                <div class="row">
                    <div class="col-md-12">
                        @RenderBody()
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

@section Scripts {
    @RenderSection("Scripts", required: false)

<script>
    $(function () {
        var current = location.pathname;
        $('.nav-tabs li a').each(function () {
            var $this = $(this);
            if (current.indexOf($this.attr('href')) !== -1) {
                $this.addClass('active');
            }
        })
    })
</script>
}

These are the areas that i want to change the background color for:

<li class="nav-item">
       <a class="nav-link active" href="/Identity/Account/Register">Sign up</a>
</li>

.nav-link >.active would select a (direct) child element of the element which has the .nav-link class. But in your case the .active class is applied to the .nav-link element itself (as an additional class) – see your example <a class="nav-link active" href="/Identity/Account/Register">Sign up</a>

So the selector for that has to be .nav-link.active {... } (without a space in -between), which selects any element that has both of these classes.

According to your css .nav-link >.active the nav-link doesnot have a direct child element so it will not work.

So, First solution change class in your css.nav-link to.nav-item

.nav-item > .active {
    background-color: var(--bg);
    color: var(--color-text);
}

Or, you can also do.

.nav-link.active {
    background-color: var(--bg);
    color: var(--color-text);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM