skip to Main Content

If the css is only on one page in razor pages should I still write in in wwwroot or have it only on the page? What is best approach with minimal size?

I’m learning about Razor pages and thinking about the correct way of doing things. What is the right way?

2

Answers


  1. From .Net 6, There is a new feature called CSS Isolation for Razor Page/view.

    CSS isolation means creating a CSS file like .cshtml.css for each razor page/view(.cshtml). CSS isolation helps to avoid dependencies on global styles that will be very hard to maintain and also avoid style conflicts among the nested content.

    In this isolation process, the style defined in the .csthm.css file are scoped and they are applied to respective razor pages/views. For example, any styling that is added in index.cshtml.css file will only apply to index.cshtml page, they won’t affect any other page in the application.

    The .NET framework runtime will bundle all the isolated CSS files(*.csthml.css) in the single file that is {your_application_name}.styles.css. So this bundled CSS line will be added automatically at {Pages/Views}/Shared/_Layout.cshml by the framework.

    The bundle CSS file({your_application}.styles.css) can maintain styles of each file without any conflict with the help of applying scope identifier like b-{10_character_string}. So the scoped identifier b-{10_character_string} will be unique for each file.

    More information you can refer link1,link2.

    Login or Signup to reply.
  2. If you are concerned about minimising size and HTTP requests, you can use a section to output the CSS styles for a specific page:

    @section css{
        <style>
        .local-style{color:blue;}
        </style>
    }
    

    Then in your layout:

    <head>
        ...
        @RenderSection("css", required:false)
    </head>
    

    That way, the css will only be rendered for the specific page. Note that CSS isolation, which has also been mentioned, bundles all isolated styles into one file which is included in every page, so you gain nothing over just adding your page-specific styles to a site.css file.

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