Why does ASP.Net RadioButton and CheckBox render inside a Span? Why does ASP.Net RadioButton and CheckBox render inside a Span? asp.net asp.net

Why does ASP.Net RadioButton and CheckBox render inside a Span?


This was driving me crazy too until I found the inputAttributes property.

For example, here is how to add a class directly on the checkbox control without the span nonsense:

myCheckBoxControl.InputAttributes.Add("class", "myCheckBoxClass")


Web controls in the System.Web.UI.WebControls namespace may render differently in different browsers. You can't count on them rendering the same elements always. They may add anything that they think is needed to make it work in the specific browser.

If you want to have any control over how the controls are rendered as html, you should use the controls in the System.Web.UI.HtmlControls namespace instead. That is:

<input type="checkbox" id="CheckBox1" runat="server" class="myClass" /><input type="radio" name="RadioButton1" runat="server" class="myClass" /><input type="text" id="TextBox1" runat="server" class="myClass" />

They will render just as the corresponding html element, with no extra elements added. This of course means that you will have to take responsibility for the browser compatibility, as the control doesn't. Also, those controls doesn't have all the features of the controls in the WebControls namespace.


Every WebControl by default renders as a <span> tag, plus any custom rendering that the control author adds.

One of the first things you usually do when you write a custom WebControl is to override the "TagKey" property to render a div, or something besides a span. The default value of this property is HtmlTextWriterTag.Span.

You could subclass your checkbox items and override the TagKey property to render something else, but then you have to deal with making all your checkboxes into your own version.