16

根据我运行的一个简单测试,我认为不可能将内联 <style> 标记放入 ASP.NET 服务器控件中。该样式最终没有呈现到输出 HTML。即使有可能,我敢肯定这样做是不好的做法。

是否有可能做到这一点?我可以看到它对于只有 1 或 2 个 CSS 类要应用的快速原型很有用。

4

4 回答 4

51

Intellisense 不会给你提示,但你可以这样做:

<asp:Label ID="Label1" runat="server" Text="Label" style="color:Red;"></asp:Label>
于 2008-09-18T13:25:49.193 回答
13

根据www.w3schools.com

样式元素位于头部。如果要在页面中包含样式表,则应在外部定义样式表,并使用<link>.

所以<style type="text\css"></style>在控件中包含样式元素(例如块)不是一个好主意。如果可以的话,它可能会在某些浏览器中产生影响,但它不会验证并且是不好的做法。

如果您想将样式内联应用于元素,那么这些都可以工作:

C#

myControl.Attributes["style"] = "color:red";

myControl.Attributes.Add("style", "color:red");

VB.NET

myControl.Attributes("style") = "color:red";

myControl.Attributes.Add("style", "color:red");

但请记住,这将替换在 style 属性上设置的任何现有样式。如果您尝试在代码中的多个位置设置样式,这可能是一个问题,因此需要注意。

最好使用 CSS 类,因为您可以将多个样式声明分组并避免冗余和页面膨胀。从WebControl派生的所有控件都有一个可以使用的CssClass属性,但再次注意不要覆盖已在其他地方应用的现有类。

于 2008-09-18T13:37:14.487 回答
7

如果使用 Attributes["style"],则每次调用时都会覆盖样式。如果您在两个不同的代码部分中进行调用,这可能是一个问题。同样,这也可能是一个问题,因为该框架包含用于基本设置的属性,例如边框和颜色,这些属性也将作为内联样式应用。这是一个例子:

// dangerous: first style will be overwritten
myControl.Attributes["style"] = "text-align:center";
// in some other section of code
myControl.Attributes["style"] = "width:100%";

为了玩得更好,请设置这样的样式:

// correct: both style settings are applied
myControl.Attributes.CssStyle.Add("text-align", "center");
// in some other section of code
myControl.Attributes.CssStyle.Add("width", "100%");
于 2014-06-30T14:40:01.050 回答
1

我认为您必须将其作为属性添加到服务器控件...才能呈现为 HTML。

所以基本上(在 C# 中),

ControlName.Attributes["style"] = "color:red";
于 2008-09-18T13:17:57.137 回答