Should I give <label> an id attribute?

I was wondering what I should put inside the label element.

For example, is this correct?

< label> Name:< /label>
< input id=“name” type=“text” required>

or should I also give the label an id? < label id=“label”> Name:< /label> >

When I searched online for label I saw some code like this:
< label for=“name”>Name:< /label> >

I’m a bit confused when I should, and when I should not use an id attribute in an element.

  **Your code so far**
/* file: index.html */
<!DOCTYPE html>
<html>
<head>
  <title> Survey Form </title>
  <meta charset:"utf-8">
  <link rel="stylesheet" href="styles.css">
</head>

<!--
* Title is for search engine optimization
* Charset is for encoding 
* link links HTML with CSS
-->

<body>
  <h1 id="title">Survey Form</h1>
  <p id="description">We appreciate you taking the time to help us!</p>
  <form id="survey-form">
  <label for="name"> Name:</label> 
  <input id="name" type="text" required> 
    </form>
</body>

<!--

-->

</html>
/* file: styles.css */

  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36

Challenge: Build a Survey Form

Link to the challenge:

You don’t need to put an id on an element unless you are going to use it for something, so in this case I would say no, you don’t need to add an id to the label. But you do have an id on the input, which is good, because you will use it for something. In order to associate the label with the input you need to add a for attribute to the label. The value of the for attribute is the id of the input that it is associated with.

1 Like

Hmm so should I get used to automatically using the for attribute inside the label when I have a input below it? or is the < label> Name:< /label> also correct most of the time?

Also could you maybe elaborate on

Does this mean that if I want to change the color of only the Name text (before the input) I should give it an ID?

Yes. For accessibility, best practices dictate that you always have a for attribute on a label, no matter where the input is located.

Yes, you can use ids to target an individual element with CSS. But if you want to target several elements at one time then it is best to use classes. But you will definitely need ids for things like the for attribute. There are also other accessibility related attributes that require ids.

1 Like

Ah thanks for the in depth reply. I’ll keep that in mind!

Appreciate the quick answers. :+1:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.