Search code examples
htmlsemantic-markup

How to group labels in html5?


How can I group labels in a semantic way? e.g.:

If I was making a form about favorite foods, as in:

<form> 
  <label for="food1">Rice</label>
  <input type="checkbox" id="food1" name="food"><br>
  <label for="food2">Pasta</label>
  <input type="checkbox" id="food2" name="food"><br>
  <label for="food3">Meat</label>
  <input type="checkbox" id="food3" name="food"><br><br>
  <input type="submit" name="submit" value="submit">
</form>

Would I put a <h2>Favorite foods</h2> before them or is there any more semantically appropriate tag for it?


Solution

  • The question is pretty general and kind of boils down to preference, but you could use a fieldset tag to group the fields, and then use a legend tag for the header.

    <form>
      <fieldset>
        <legend>Favorite Foods</legend>
        <label for="food1">Rice</label>
        <input type="checkbox" id="food1" name="food"><br>
        <label for="food2">Pasta</label>
        <input type="checkbox" id="food2" name="food"><br>
        <label for="food3">Meat</label>
        <input type="checkbox" id="food3" name="food"><br><br>
      </fieldset>
      <input type="submit" name="submit" value="submit">
    </form>