[英]How can i add css to a dynamically created div in c#?
i am using css to configure this div's properties using it's id, but it aint working, maybe because i created it in c# in the code behind, how can i fix that? 我正在使用css使用它的id配置此div的属性,但是它不能正常工作,也许是因为我在后面的代码中用c#创建了它,我该如何解决?
c# C#
StringBuilder sb = new StringBuilder();
sb.Append(@"<div id=""img1"" runat=""server"">Vidal</div>");
Label1.Text = sb.ToString();
Css CSS
#img1{
position: absolute;
top: 20px;
left: 20px;
width: 253px;height: 190px;
} }
I would use a class instead of an ID. 我将使用类而不是ID。 Also, you don't need to make it a div, as your Label will render as a span. 另外,您无需将其设为div,因为您的Label将呈现为跨度。 You simply need to set the CssClass
and Text
properties. 您只需要设置CssClass
和Text
属性。
Label1.CssClass = "someClass";
Label1.Text = "Vidal";
.someClass
{
position: absolute;
top: 20px;
left: 20px;
width: 253px;
height: 190px;
}
you can't use label control to display html content , use literal control or panel like below 您不能使用标签控件来显示html内容,不能使用文字控件或下面的面板
Panel div = new Panel();
div.ID = "img1";
div.Controls.Add(new Literal{Text = "Vidal"});
this.Controls.Add(div);
I think for your purposes, you might be better with asp:literal control: 我认为出于您的目的,使用asp:literal control可能会更好:
StringBuilder sb = new StringBuilder();
sb.Append("<div class=\"image-css-selector">Vidal</div>");
Literal1.Text = sb.ToString();
A label control will have it's own markup and that might affect your html code 标签控件将具有自己的标记,这可能会影响您的html代码
If you are using a single webform, then please make sure that you do not have multiple ids. 如果您使用的是单个Web表单,请确保您没有多个ID。 If you are using a master page, and you really need a runat="server
attribute to the div then you need to change the css like this: 如果您使用的是母版页,并且确实需要对div使用runat="server
属性”,则需要像这样更改css:
#ContentPlaceHolder_img1{
position: absolute;
top: 20px;
left: 20px;
width: 253px;height: 190px;
Where ContentPlaceHolder
is the name of the ID that you have gave for your content placeholder. 其中ContentPlaceHolder
是您为内容占位符提供的ID的名称。 for ex: 例如:
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
In your master page. 在您的母版页中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.