简体   繁体   中英

Add a CSS file to an aspx file

I have an ascx page on which I want to add a link to a css file.

For this I use :

<link href="myCSS.css" rel="Stylesheet" type="text/css" />

But it doesn't work.

I also try this on the code behind :

System.Web.UI.HtmlControls.HtmlLink link = new System.Web.UI.HtmlControls.HtmlLink();
link.Href = "myCSS.css";
link.Attributes.Add("rel", "stylesheet");
link.Attributes.Add("type", "text/css");
link.Attributes.Add("title", "Default");
this.Page.Header.Controls.Add(link);

And this :

System.Web.UI.HtmlControls.HtmlGenericControl myCss = new System.Web.UI.HtmlControls.HtmlGenericControl();
myCss.TagName = "link";
myCss.Attributes.Add("type", "text/css");
myCss.Attributes.Add("rel", "stylesheet");
myCss.Attributes.Add("href", ResolveUrl("myCSS.css"));
this.Page.Header.Controls.Add(myCss);

I put this ascx file on an aspx file which uses a masterpage, maybe the problem is here ?

EDIT

The problem is the intellisense see the file (because it show my CSS classes in the file), but it doesn't apply them on my ascx file.

 <link href="../Mycss.css" rel="stylesheet" type="text/css" />

尝试这个

The code you have the minute would assume the CSS file is located in the same directory as your ascx file, you should resolve the path so it always comes from the root of the site ie

<link href='<%=ResolveUrl("~/myCSS.css")%>' rel="Stylesheet" type="text/css" />

You could also try just adding the backslash (if they are in the same directory) ie

<link href="/myCSS.css" rel="Stylesheet" type="text/css" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM