Say I have an input field and next to it I have text. Should the text always be enclosed in a html tag? If so why?
First name: <input type="text" name="fname">
VS
<label for="fname">First name:</label> <input type="text" name="fname">
Tags are always enclosed in angle brackets: < >. Tags are comprised of elements and attributes. An element is an object on a page (such as a heading, paragraph, or image), and attributes are qualities that describe that element (such as width and height). Tags usually travel in pairs.
A few tags are called non-container tags, because they don't contain any content - they stand alone. Examples are images and line breaks. XHTML is more strict than HTML, and requires that all open tags must be closed, even if they're not container tags.
There are some HTML elements which don't need to be closed, such as <img.../>, <hr /> and <br /> elements. These are known as void elements.
Not closing tags can lead to browser incompatibilities and improperly rendered pages. That alone should be enough reason to properly close your tags.
Label in this case allows you to click on the label itself - and it will give focus to the input with the id supplied in the for
attribute. It's recommended for usability.
Just make sure to set the input's id
that the label's for
is set to the inputs id
.
Definitely this way:
<label for="fname">First name:</label> <input type="text" name="fname" id="fname">
The browser understands the connection between for
attribute of label
and id
attribute of input
.
The result is (for example), you can click the label
and coresponding input
gets focus.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With