Along with input fields, labels are often used, which are represented by the label element . Labels create an annotation or heading for an input field, indicate what the field is for.
To associate with an input field, the label has a for attribute that points to the id of the input field:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Label In HTML5</title> </head> <body> <form> <div class="form-group" style="margin-bottom: 15px;"> <label for="login">Login: </label> <input type="text" autofocus id="login" name="login" /> </div> <div class="form-group" style="margin-bottom: 15px;"> <label for="password">Password: </label> <input type="password" id="password" name="password" /> </div> <div class="form-group"> <button type="submit">Submit</button> </div> </form> </body> </html>
So, the text box here has an attribute id=”login”. Therefore, an attribute is set on the associated label for=”login”. Clicking on this label allows you to move the focus to the text field for entering the login:
Actually, this is where the role of labels ends. We can also set autofocus by default to any input field. The autofocus attribute is used for this:
<form> <div class="form-group"> <label for="login">Login: </label> <input type="text" autofocus id="login" name="login" /> </div> <div class="form-group"> <label for="password">Password: </label> <input type="password" id="password" name="password" /> </div> <div class="form-group"> <button type="submit">Submit</button> </div> </form>
Here, when the page starts, focus immediately goes to the text field.