Over the past few weeks, I have been working on a Web Application using ASP.NET Core and Razor Pages. The thing that kept frustrating me is how quickly
site.css got really big and more difficult to maintain and read. After doing some research online, I found out how to solve that problem. Let's learn how.
First, it is important to know how Razor Pages figures out how to load your css file. By default, on runtime, The engine reads the file
_ViewStart.cshtml to know which layout to load for your page and the link to the default style sheet can be found in it.
Notice that bootstrap is loaded by default and then the default
site.css is loaded. This master page will load these two files to all child pages that use it, such as
Say that you are developing an application to help users track their book readings, which page they are currently on in which book, and what books they want to publicly share on their feed.
Now say you want to define custom css to pages that belong to a certain group. For instance, you want specific styles for authentication and user pages and other styles for the rest of the web application.
Essentially, you want the
_Layout to dynamically load the css file based on the child page. The trick that will dynamically load a chosen css file into a child page will be done by using the RenderSection feature of ASP.Net Core. That can be done in three simple steps.
The third step is to reference this section with the link to your chosen style sheet on your page. For example, on the page
Views/User/Register.cshtml we want to load
user.css instead of
site.css. Be sure to reference
site.css in all other default pages in the same way as well.
By now, you're done!! Let's give it a little test in which we load two pages and inspect their CSS files. The two pages will be
View/Home/Index.cshtml (default) and
Hope this article helped maintain your styles in an easier manner. Have a good one.
Credit: Cover Photo by RhondaK Native Florida Folk Artist on Unsplash.