Nesting <label>

Is it possible to nest a <label> in another <label> in case of radio buttons like this:

**<label** for="sex"> Sex : <label for="male"><input type="radio" name="sex" id="male"></label> <label for="female"><input type="radio" name="sex" id="female"></label>**</label>**

My reason is if I separate the “Sex” from both labels there’s a gap in between both elements which I really want to get rid off and I was hoping this would still work if I have the code that way?

Hi @teamie !

If you run your code through the html validator then you will find that you can’t do that because it will come back with errors.

Try running this code and you can see the error messages for yourself.

<!DOCTYPE html>

<html lang="en">

<head>
  <meta charset="utf-8">

  <title>Labels</title>

</head>

<body>
  <label for="sex"> Sex : <label for="male"><input type="radio" name="sex" id="male"></label> <label for="female"><input type="radio" name="sex" id="female"></label></label>
</body>

</html>

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like

It is a label, so it is just text the user sees.

How things look to you in the code aren’t necessarily how it will render on the page that the user of the page will see.

Nesting that way is not “valid” html because of the way the html interpreter parses the html, and also, it is easy to forget to close a tag in very long code/page with lots of tags.

You want the code, over all, to be easily readable by your future self and other developers to find and fix errors and easily see which closing tags belong with which opening tags.

For situations where layout, spacing, styling matters, you will learn about styling, spacing, positioning, in the CSS portion of the curriculum.

Thank you @jwilkins.oboe I guess I’ll have to try using CSS to fix the error instead.

Thank you for the analysis @a_aramini will put these into consideration. Still trying to totally grasp my CSS that’s why I tried compromising with the <label> tag.

If you get stuck and need help with the CSS, you can also paste your full HTML and CSS code in a new topic, describing your CSS issue (making sure to format it as @jwilkins.oboe instructed above).

Or provide a link to your Codepen or Github if you are using those, so someone could take a look and guide you in the right direction.

It would clarify and help us better understand what you mean by:

If I change the code you have pasted here so far to this:


<html lang="en">

<head>
  <meta charset="utf-8">

  <title>Labels</title>

</head>

<body>
Sex:
<label for="male"><input type="radio" name="sex" id="male" value ="male">male</label>
<label for="female"><input type="radio" name="sex" id="female" value="female">female</label>
</body>

</html>

It looks like this:
image

I see spaces between the label and first radio button, and between both radio buttons, if that’s what you’re referring to. But it’s hard to know exactly what you want by going off of just just that code.

Also, I noticed you haven’t put a value= attribute in your radio buttons, don’t forget to do that or the form will have no data to post for those fields. If one is selected and there is no value= then the default value will be “on” which is ambiguous data because you will have no way of knowing which one is selected.

You don’t use HTML elements to do this, not the way you’re trying to do. <label> has specific meaning (it is literally a label for a specific input), it’s not a way to style things. You can’t put a label in a label because it doesn’t make sense. Yes, you use CSS for this.

1 Like

Yes, that.

I did a poor job of trying to generally convey this:

I don’t know the impact of doing it the “incorrect” way as shown in that graphic as far as how different browsers will interpret and render (if at all) the page or if it would cause anything other than a warning in a validator. I’ve haven’t tested it (easy to test though). But I learned that you aren’t supposed to do it that way.

I think if you have a lot of that kind of spaghetti going on in your HTML, a lot of improperly nested tags n levels deep, it would at the very least, be confusing for a human to read… and, of course, it is outside of the HTML specifications.

Thank you for the explanation @a_aramini. I was able to separate all <label> tags and instead I made use of CSS to adjust the distance between the elements and yes I did put having the value attr into consideration. This is the original code which I am currently working on:

<label for="test-urgency">Test Urgency:</label>

<label for="yes">
    <input  type="radio" 
            name="test-urgency"
            value="yes"
            id="yes">Yes
            
</label>

<label for="no">
    <input  type="radio"
            name="test-urgency"
            id="no"
            value="no"
            checked >No
</label>

This is what it looks like:
Screenshot 2021-05-30 093128

Do you think there’s a better way to have nested this?

1 Like

It actually made no sense to me at first I was probably just compromising now I know better than to try using HTML for styling instead of CSS. Thanks @DanCouper

That looks good to me. Good job!

One thing I should also mention is that you really don’t need the

for="test-urgency"

in

<label for="test-urgency">Test Urgency:</label>

“Test Urgency” is just a label for the fields as a group of inputs, but by itself, it has no inputs.

It is just a caption, a descriptor, for all of the related radio inputs.

So you could just do this:

<label>Test Urgency:</label>

You could also use the <legend> tag for that.

There’s also a <fieldset> tag which is used to group related elements in a form.

You could do something like this:

<fieldset>
<legend>Test Urgency:</legend> 

<label for="yes">
    <input  type="radio" 
            name="test-urgency"
            value="yes"
            id="yes">Yes
</label>
<label for="no">
    <input  type="radio"
            name="test-urgency"
            id="no"
            value="no"
            checked >No
</label>
</fieldset>

You don’t necessarily have to use the <fieldset> tag, it groups related elements in a form together and draws a box around the related elements. So maybe you don’t want to wrap everything in that tag. That’s up to you.

HTML Fieldset Tag

The <legend> tag defines a caption for the element.

HTML Legend Tag

Then you do your styling and positioning accordingly using CSS.

If you don’t want to mess up your current existing code, you can experiment with it in the w3schools “Try It” editor:

Try It Editor - Fieldset tag

Something to keep in mind when designing a form is that it’s not just the presentation and accessibility to the user that is important.

You’re asking for that form data for a reason :smiley:

The form data is ultimately going to be sent to a script on a server (Node.js, PHP, Python, etc) for processing on the back-end to be stored in a database, perform some calculation and send it back to the page, or populate data in some other page or something like that.

So you want the associated labels, descriptors, values, etc on the front end (the form fields, inputs etc.,) to make sense when they are received on the back-end.

That makes it easier for the back-end developer (yourself or someone else) to write the program logic in the script which handles the data on the back-end.

For the HTML projects on FCC, I don’t think it’s actually sending your data anywhere, but in a real world use case, it would.

Thank you so much @a_aramini this was really really helpful… I have adjusted my code accordingly.

<fieldset>
    <legend>Test Urgency:</legend>

    <label for="yes">
        <input  type="radio" 
                name="test-urgency"
                id="yes">Yes
    </label>
    
    <label for="no">
        <input  type="radio"
                name="test-urgency"
                id="no" 
                checked >No
    </label>
</fieldset>

Also used some CSS to style it to look like :
Screenshot 2021-05-30 141951

In terms of appearance I’m not quite sure if this is acceptable in a form… or what do you think?

Here’s a copy of my CSS:

fieldset{
    width:150px;
    margin-left: 270px;
    padding-right: 50px;
    display: flexbox;
}

Yes, that looks really nice!

I personally like the way <fieldset> groups everything together nicely, makes it more clear to the user filling out the form. That’s just my personal opinion though.

Some key things to be keep in mind when designing forms:

  • Make sure the HTML tags and CSS are used correctly

  • Make sure the form makes sense in terms of usability by the user filling it out

  • Make sure you have defined a value attribute for all inputs.

    • For user fill-in inputs such as Name, Phone Number, Email, etc., the value will be what the user types into the field. You can set a default value if you wanted but for these, typically you just leave them empty like this: value="". The user will fill it in and you will capture its data in the form submission.

      But for things like checkbox and radio button inputs, omitting a value attribute from the input element can have unexpected behavior.

      Consider this scenario for a radio button:

      You have a form section labeled “Favorite Color” and have a radio button for each option, “Red”, “Green”, “Blue”. But you forget to set the value attribute for each radio button with a corresponding value that represents the selection the user can make.

      Well, the the default value for the selected radio button is going to be "on" because radio buttons can only be in an "on" (selected) or "off" (not selected) state, like a switch. If nothing is selected, nothing is sent. One might think "off" will be sent, but that is not the case.

      So for this:

      <fieldset>
      <legend>Favorite Color:</legend>
      
      <label for="favorite-color">
        <input  type="radio" 
                name="favorite-color"
                id="red">Red
      </label>
      
      <label for="favorite-color">
        <input  type="radio"
                name="favorite-color"
                id="green">Green
      </label>
      <label for="favorite-color">
        <input  type="radio"
                name="favorite-color"
                id="blue">Blue
      </label>
      </fieldset>
      

      favorite-color="on" doesn’t make sense. When we receive the data on the back-end, we know a selection was made, but which selection was made? How do we capture the corresponding value that the user chose?

      In your case, you are using it to get the answer to a question that can only have a "yes" or "no" answer. So test-urgency="on" makes sense if "yes" is selected.

      But what if "no" is selected? Then we still have "test-urgency="on" because the default value for a selected radio button with no value attribute is "on". Hmm kinda confusing now, isn’t it? Lack of setting a proper value attribute has introduced ambiguity.

      This is why creating a value= attribute for each input, with a unique value corresponding to what the radio button represents, becomes important.

      Also, if you make a typo in the name of a radio button that is in a group (grouped by name), it will act as an independent selection and the radio button behavior will be broken. You would be able to select that radio button and one radio button from the group, because they are no longer in the same group due to the name typo. So pay close attention to your names as well! They need to match exactly to work together in group.

  • Make sure you haven’t mixed up your names and values so that it makes sense on the the back-end.

    • The name and value pairs for each input field is what gets sent to the server upon submission. They are stored in variables, which are the names of the inputs.

    • The back-end can then access and use these to manipulate the data, or store it a database.

    • For example, you’d want to make sure that the values get stored in the proper corresponding table, row, column in the back-end database.

      (This will make more sense if you ever get into back-end development and play around with submitting an HTML form to a MySQL or MariaDB database).

With those points satisfied, the layout, positioning, style, decorations, colors, etc all come down to your personal preference.

Good job!

Thanks so much @a_aramini for taking your time to explain all of these extensively… It was really helpful :grinning_face_with_smiling_eyes:

You’re welcome! It also helped me clarify in my own head while trying to clarify it to you, as I haven’t done HTML or forms in quite a while. And, I wanted it to be useful and make sense to other users if they search the forum and are having a similar issue. :wink:

If I have any errors or mistakes, I definitely welcome corrections. I don’t want to give anyone misinformation :smiley:

1 Like

Thanks a lot once again @a_aramini … Looking forward to uploading it on the MySQL server and testing out the functionality of the form with all corrections made.

1 Like

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