开发者

Error Message: <span> vs <label>

开发者 https://www.devze.com 2023-02-05 11:55 出处:网络
When you display an error message in HTML, which element do you use, <span> or <label>? Can you list some pros and cons for each of them, assuming that some styling, such as co开发者_如何

When you display an error message in HTML, which element do you use, <span> or <label>?

Can you list some pros and cons for each of them, assuming that some styling, such as co开发者_如何学Pythonlor and margin will be applied through their class?


Assuming you mean an error message associated with a specific form control, use a <label>.

The semantic arguments are subject to debate, as they aren't clear cut in this case, but the practical arguments win quite nicely. If a screen reader is in forms mode, it may skip over non-label text thus hiding the error messages from the user.


Either can be used and both can be styled. I think the discussion will be about symantically which is more clear. I think of label elements as being associated with describing what a particular input element's intent. I don't feel displaying error info fits this and prefer the span.


AFAIK, the purpose of a label is that clicking on the label clicks the control that it is "for". This is very helpful for things like checkboxes and radio buttons, where the actual control is small and tricky to click.


I would suggest markup like this

<label for=i123>Full name:
<strong class=error>Full name must contain as least some whitespace in the middle.</strong>
<input id=i123 type=text name=fullname>
</label>

Rationale:

Having the label text and the error message within the same <label> allows screen readers to read all the text related to text input in known order. You should also try to use attribute pattern for the <input> element if you can describe the requirements that way. Even though the specs allow multiple label elements to be attached to single real world assistive technology is known to have problems with such content in practice. The <label> and <input> can be put next to each other long as you use for and id attributes - nesting allows removing those attributes if you want to minimize the markup. Historically MSIE had problems with <label> elements without for attribute.


http://www.w3schools.com/tags/tag_label.asp: "The tag defines a label for an input element."

For regular inline text, use span.


I'm likely to use <span> because each input field already has a <label> and it never occured to me to have two labels for one input field.


This answer was wrong: see comments below.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号