skip to Main Content

I am trying to style NavLink in Blazor with a CSS class that I have in a CSS Isolation file for that razor file. I just do not seem able to make any changes accept with global or inline styles.

sample.razor

<NavLink href="" class="cssLink">A Link</NavLink>

sample.razor.css

cssLink {
  color: #10069f;
  text-decoration: none;
  transition: all 0.1s linear;
}

cssLink:hover {
  color: #4a4a4a;
  text-decoration: none;
}

2

Answers


  1. You have two problems here. The first one is the CSS selector because simply writing cssLink as selector means there is an element of type cssLink. To select a elements by their class you have to place a dot before the class name so correctly would it be:

    .cssLink {
      color: #10069f;
      text-decoration: none;
      transition: all 0.1s linear;
    }
    
    .cssLink:hover {
      color: #4a4a4a;
      text-decoration: none;
    }
    

    The second problem is caused by the default behavior CSS isolation. By default these rules are only applied in their component which is the sense of isolation. To get around this you have to use the ::deep pseudo element to tell Blazor that it should apply these rule also for child components. You fixed CSS code looks this:

    ::deep .cssLink {
      color: #10069f;
      text-decoration: none;
      transition: all 0.1s linear;
    }
    
    ::deep .cssLink:hover {
      color: #4a4a4a;
      text-decoration: none;
    }
    
    Login or Signup to reply.
  2. You could try to add the NavLink in a div to be able to apply the css:

    <div class="nav-container">
       <NavLink href="">A Link</NavLink>
    
    </div>
    

    css:

    ::deep a.active{
        color:brown;
    }
    

    Just make sure to put the .razor.css file in the same directory as the .razor file.

    Result:

    enter image description here

    Refernce:

    https://learn.microsoft.com/en-us/aspnet/core/blazor/components/css-isolation?view=aspnetcore-8.0

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search