How to include CSS in master pages?
How do I include CSS reference in only certain pages on my asp.net website开发者_如何学编程? If I include the reference in my master page, all pages of the website share the CSS reference.
Just add a CSS ContentPlaceHolder with a default value in it.
Basically, the CSS file you specify as default will be included unless you override that placeholder with an <asp:Content />
tag from a child page.
Your Master Page should look something like this.
<head>
<asp:ContentPlaceHolder ID="Stylesheets" runat="server">
<link rel="stylesheet" href="/css/master.css" type="text/css" />
</asp:ContentPlaceHolder>
</head>
Then from any pages using that Master Page, you can simply override that with a different stylesheet.
On (example) AboutUs.aspx
<asp:Content ID="Content1" ContentPlaceHolderID="Stylesheets" runat="server">
<link rel="stylesheet" href="/css/form.css" type="text/css" />
</asp:Content>
In my situation, i used the same masterpage from different locations in the solution. And since the ~ (Tilde) prefix on the reference to my css files, i added a response.write to the reference like so:
<%= ResolveUrl("~/css/myStyle.css") %>
You can use more than one Master page on your site.
You can also use nested master pages. The Top level might have the general site structure, and then one Master nested master page for each of your different areas.
When you right click your project and select Add, you choose the option WebContentForm, instead of WebForm. Then you can select the appropriate masterpage.
In your nested masterpages, you set the MasterPageFile equal to your top level masterpage.
Edit When combined with @Marko's approach you could have the following...
The advantage here is that all of your overrides only have to be written once.
Top Level MasterPage:
<head>
<asp:ContentPlaceHolder ID="Stylesheets" runat="server">
<link rel="stylesheet" href="/css/default.css" type="text/css" />
</asp:ContentPlaceHolder>
</head>
Nested MasterPage with no override
<%@ Page Language="C#" MasterPageFile="~/Site.master"%>
//don't reference the Stylesheets ContentPlaceHolder and the default is rendered
Nested MasterPage One with override.css
<%@ Page Language="C#" MasterPageFile="~/Site.master"%>
<asp:Content ID="Content1" ContentPlaceHolderID="Stylesheets" runat="server">
<link rel="stylesheet" href="/css/override.css" type="text/css" />
</asp:Content>
Nested MasterPage Two with secondOverride.css
<%@ Page Language="C#" MasterPageFile="~/Site.master"%>
<asp:Content ID="Content1" ContentPlaceHolderID="Stylesheets" runat="server">
<link rel="stylesheet" href="/css/secondOverride.css" type="text/css" />
</asp:Content>
Then, just set the appropriate master page on any of your web forms.
精彩评论