{"id":337074,"date":"2021-03-30T13:29:49","date_gmt":"2021-03-30T20:29:49","guid":{"rendered":"https:\/\/css-tricks.com\/?p=337074"},"modified":"2021-04-02T12:13:54","modified_gmt":"2021-04-02T19:13:54","slug":"html-inputs-and-labels-a-love-story","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/html-inputs-and-labels-a-love-story\/","title":{"rendered":"HTML Inputs and Labels: A Love Story"},"content":{"rendered":"\n

Most inputs have something in common\u2009\u2014\u2009they are happiest with a companion label! And the happiness doesn\u2019t stop there. Forms with proper inputs and labels are much easier for people to use and that makes people happy too.<\/p>\n\n\n\n\n\n\n\n

\"\"
A happy label and input pair<\/figcaption><\/figure>\n\n\n\n

In this post, I want to focus on situations where the lack of a semantic label and input combination makes it much harder for all sorts of people to complete forms. Since millions of people\u2019s livelihoods rely on forms, let\u2019s get into the best tips I know<\/strong> for creating a fulfilling and harmonious relationship between an input and a label.<\/p>\n\n\n\n

Content warning:<\/strong> In this post are themes of love and relationships.<\/p>\n\n\n\n

The love story starts here! Let\u2019s cover the basics for creating happy labels and inputs.<\/p>\n\n\n

How to pair a label and an input<\/h3>\n\n\n

There are two ways<\/strong> to pair a label and an input. One is by wrapping the input in a label (implicit), and the other is by adding a for<\/code> attribute to the label and an id<\/code> to the input (explicit).<\/p>\n\n\n\n

Think of an implicit label as hugging<\/strong> an input, and an explicit label as standing next to an input and holding<\/strong> its hand.<\/p>\n\n\n\n

<label> \n  Name:\n  <input type=\"text\" name=\"name\" \/>\n<\/label><\/code><\/pre>\n\n\n\n

An explicit label\u2019s for<\/code> attribute value must match its input\u2019s id<\/code> value. For example, if for<\/code> has a value of name<\/code>, then id<\/code> should also have a value of name<\/code>.<\/p>\n\n\n\n

<label for=\"name\">Name: <\/label>\n<input type=\"text\" id=\"name\" name=\"name\" \/><\/code><\/pre>\n\n\n\n

Unfortunately, an implicit label is not handled correctly by all assistive technologies, even if for<\/code> and id<\/code> attributes are used. Therefore, it is always the best idea to<\/strong> use an explicit label instead of an implicit label.<\/strong><\/p>\n\n\n\n

<!-- IMPLICIT LABEL (not recommended for use) - the label wraps the input. -->\n<label> \n  Name:\n  <input type=\"text\" name=\"name\" \/>\n<\/label>\n\n<!-- EXPLICIT LABEL (recommended for use) - the label is connected to an input via \"for\" and \"id\" -->\n<label for=\"explicit-label-name\">Name: <\/label>\n<input type=\"text\" id=\"explicit-label-name\" name=\"name\" \/><\/code><\/pre>\n\n\n\n