HTML <label> Tag โ Input Label
๐ Introduction
The <label> tag is used to define a text label for an input field.
It improves:
- User experience (UX)
- Accessibility (screen readers)
- Click behavior (clicking label focuses input)
๐งฑ Syntax
<label>Username</label> <input type="text" />
๐ก Example
<!DOCTYPE html>
<html>
<head>
<title>Label Example</title>
</head>
<body>
<h2>Login Form</h2>
<form>
<label>Username:</label>
<input type="text" />
<br /><br />
<label>Password:</label>
<input type="password" />
<br /><br />
<button type="submit">Login</button>
</form>
</body>
</html>
๐ฅ๏ธ Output Explanation
- Each input has a text description
- Users understand what to type
- Makes form easier to use
๐ฏ Best Practice (IMPORTANT)
๐ Connect label with input using for + id
<label for="username">Username:</label> <input type="text" id="username" />
โ Clicking the label focuses the input
๐ง Why <label> is Important
1. โฟ Accessibility
Screen readers read labels properly.
2. ๐ฑ๏ธ Better UX
Clicking the label selects the input.
3. ๐ Professional Forms
All real websites use labels correctly.
๐งฉ Example (Proper Form)
<form>
<label for="email">Email:</label>
<input type="email" id="email" />
<br /><br />
<label for="pass">Password:</label>
<input type="password" id="pass" />
</form>
โ๏ธ Label Methods
1. Wrapped Label
<label>
Username
<input type="text" />
</label>
โ No need for for and id
2. Connected Label (Best Practice)
<label for="name">Name</label> <input id="name" />
โ Recommended in real projects
๐ซ Common Mistakes
- Missing labels โ
- Not connecting with
forโ - Using placeholder instead of label โ
๐จ Styling Example
<label style="font-weight:bold;">Email:</label> <input type="email" />
๐งช Mini Exercise
Create a form with:
- Name input + label
- Email input + label
- Password input + label
- Proper
forandidconnections - Submit button