C# – Use the same CSS file for masterpage and page content

asp.netc++cssmaster-pages

I have an APS.net app (C#) with several pages that use the same MasterPage. In that page, I have included a couple stylesheets like so:

<head runat="server">
<link href="/apps/_lib/ui/styles1.css" type="text/css" rel="stylesheet" />
<link href="/apps/_lib/ui/styles2.css" type="text/css" rel="stylesheet" />
</head>

These styles apply correctly to all content that is in the actual .master file (page), but are not applied to any pages that use the Master page (for instance default.aspx uses that master page and has a Content placeholder in it).

If I add these lines in each individual page:

<link href="/apps/_lib/ui/styles1.css" type="text/css" rel="stylesheet" />
<link href="/apps/_lib/ui/styles2.css" type="text/css" rel="stylesheet" />

Then the styles show up as expected… but it was my hope that I could include them in the master page so that I didn't need to include these references in each subsequent page too.

Because these files are not located physically in the same project (they are shared between several apps), i cannot just include them as an ASP.net theme that would be applied to all pages.

Update

In order to rule out the file locations problem, I used the absolute URL for these stylesheets…

<link href="https://myserver/apps/_lib/ui/styles1.css" type="text/css" rel="stylesheet" />
<link href="https://myserver/apps/_lib/ui/styles2.css" type="text/css" rel="stylesheet" />

That way, no matter where it is read from, the file can be located. This still exhibits the same behavior.

To me, it looks like the masterPage is rendered with the CSS styles (because they're in the same file) and then the child/calling page is rendered without the CSS styles (because they aren't in that file, they're in the masterPage) and then those two files are combined together (as opposed to combining them together first and THEN rendering the style elements for the combined pages). Adding to this belief was my previous example of adding the include for the CSS file in the calling page itself, which will cause it to display the CSS correctly.

You can view the source of this file, and in the head section, you can see the CSS styles linked correctly, but they aren't applied to any elements from the calling page while they are applied to all elements in the masterPage.

Best Solution

Is the content page in a different folder that the master? If so, you'll have to get the application relative path to the css files using ResolveUrl in the master page:

<link href='<%= ResolveUrl("~/apps/_lib/ui/styles1.css") %>' type="text/css" rel="stylesheet" />

Update: If this doesn't work, then you might have HTML or CSS errors like Lance suggested. Try using the HTML and CSS validators at w3schools.com. If it still doesn't work after fixing any errors, double check your CSS selectors with the rendered HTML as Steve suggested. ASP.Net's generated IDs have bitten me more than once.