Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to style NavLink when using CSS isolation

I am trying to make a Component for buttons in my Main Menu.

<NavLink href="@Href" title="@Title">
    <div class="main-menu-button">
        <img src="@IconUrl" />
        <div class="label">
            @Label
        </div>
    </div>
</NavLink>

@code {

    [Parameter]
    [EditorRequired]
    public string? Href { get; set; }

    [Parameter]
    [EditorRequired]
    public string? Label { get; set; }

    [Parameter]
    public string? Title { get; set; }

    [Parameter]
    [EditorRequired]
    public string? IconUrl { get; set; }
}

I can't seem to target the NavLink in my css file. I've tried all of these different variations, but the button never changes color when active.

::deep a.active {
    background-color: red !important;
}

::deep .active {
    background-color: green !important;
}

::deep a .active {
    background-color: blue !important;
}

a.active {
    background-color: yellow !important;
}

a .active {
    background-color: orange !important;
}

I can see that the active class is present when I inspect element. I know my CSS isolation is working, because I am able to add styles that target the inner elements.

This problem is not limitted to the active class. I am also unable to target the NavLink element to set 'text-decoration:none in css.

like image 694
Dave Avatar asked Jun 10 '26 19:06

Dave


1 Answers

Css isolation works by adding a custom scope identifier to all html elements of the component. As a result, the css you wrote

::deep a.active {
    background-color: red !important;
}

turns into something like the following

[b-zbwm49ki0i] a.active {
    background-color: red !important;
}

The above css, means select all a elements that have an active class that are inside elements that have a b-zbwm49ki0i attribute. In your example, there is no element with the custom scope identifier as a parent to the Navlink, so the css is not applied. In other words, you need to wrap your NavLink in a div to be able to apply the css. This makes sure the link is in side an element with a custom scope identifier.

<div>
    <NavLink href="@Href" title="@Title">
        <div class="main-menu-button">
            <img src="@IconUrl" />
            <div class="label">
                @Label
            </div>
        </div>
    </NavLink>
</div>
like image 108
Jesse Good Avatar answered Jun 12 '26 10:06

Jesse Good



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!