Overriding ASP.NET Theme CSS Files with Conditional Comments

One of the biggest annoyances in ASP.NET is the way it adds CSS files to your element of your pages. It insists on adding them to the end, offering you no way to add your own custom styles that override the theme unless you go down the line and add !important to each element.

This is especially detrimental if you're trying to add IE-only stylesheets using conditional comments. Since the theme files are loaded after the IE stylesheet, all your custom styles will be overridden as if it was not present at all.

There are some hacks, from using the script manager to inject css (which doesn't work because this doesn't inject it into the section) to a full fledged custom control that automates this for you.

I needed something quick and dirty, so I hacked a solution by overriding the Render method of the site's Master Page and injecting an HTML Literal control with the IE conditional comments.

protected override void Render(HtmlTextWriter writer)
{
    // IE conditionals string css = @" <!--[if IE]> <link rel=""stylesheet"" type=""text/css"" href=""/css/ie.css"" /> <![endif]--> ";
    // add conditional text to head var ctrl = new Literal();
    ctrl.Text = css;
    Head1.Controls.Add(ctrl);
    base.Render(writer);
}

Apparently this is late enough in the page life-cycle to be added after the Theme files, and it works like a charm!

I thought this was addressed in 4.0, but I can't seem to find anywhere to specify a custom location for the theme css files, nor any simple way to specify additional files afterwards. If there is a simple, built-in solution to this problem, please let me know in the comments!

Enjoyed this post and/or found it useful?
SelArom Dot Net Profile Image
SelAromDotNet

Josh loves all things Microsoft and Windows, and develops solutions for Web, Desktop and Mobile using the .NET Framework, Azure, UWP and everything else in the Microsoft Stack.

His other passion is music, and in his spare time Josh spins and produces electronic music under the name DJ SelArom.



Scroll to top