Search code examples
cssasp.net-mvcrazor

How to reference a .css file on a razor view?


I know how to set .css files on the _Layout.cshtml file, but what about applying a stylesheet on a per-view basis?

My thinking here is that, in _Layout.cshtml, you have <head> tags to work with, but not so in one of your non-layout views. Where do the <link> tags go?


Solution

  • Starting with .NET 6, you can add a css file alongside your cshtml files.

    For example:

    WebApp/Pages/
    ├── Index.cs
    ├── Index.cshtml
    ├── Index.cshtml.css <-- NEW
    

    This will generate a file {ASSEMBLY NAME}.styles.css which you must include in your shared _Layout.cshtml.

    Configure _Layout.cshtml to include .cshtml.css styles

    (Replace WebApp with the name of your csproj file.)

    <!DOCTYPE html>
    <html>
    
    <head>
    +    <link rel="stylesheet" href="~/WebApp.styles.css" asp-appendversion="true" />
    </head>
    
    ...
    
    </html>
    

    Doing it this way has the additional benefit that the styles are isolated, and won't accidentally leak outside the Razor page where they are used. For example, you can add a style for <p>.

    /* in Index.cshtml.css */
    p {
        color: red;
    }
    

    When the project is built, the HTML and CSS are transformed to include a randomized attribute name.

    /* Transformed css */
    p[b-ruxg182vl6] {
        color: red;
    }
    

    Similarly, the <p> tags in Index.cshtml are decorated with this attribute.

    <p b-ruxg182vl6>Hello World</p>
    

    This way, only the paragraphs in Index.cshtml will have the red color. Paragraphs in other parts of your application are not affected.

    Full documentation about CSS isolation: https://learn.microsoft.com/en-us/aspnet/core/blazor/components/css-isolation