Page Specific CSS in Core MVC

1/30/2018 12:00:00 AM


Say you are creating a website that has different pages (in my case a blog), And on one of those pages you need to include a specific style sheet that the rest of the pages do not use.  You are in luck, because it can be done easily with sections.  

In the view that needs a different CSS, create a section and put the CSS in it like so:

@section cssSection { <link rel="stylesheet" href="~/css/myStyle.css"> }

In the shared layout view (_Layout.cshtml), render the section inside of the header:

  @RenderSection("cssSection", false)

The first parameter is the section name we defined in our view. The second parameter says whether or not rendering the section is required.

And that's all there is to it!  The css should now be included with your html page.