Adam Hughes
Adam Hughes

Reputation: 2277

Is using a HTML Label to wrap elements semantic?

I'm considering using a label to wrap a h3 and a p tag. In my mind this makes sense as the label has a heading and description and both relate to the input. However I can't seem to find any info in the spec on whether this can be done.

Here is an example:

<label for="test1">
    <h3>Label Heading</h3>
    <p>Label Description</p>
</label>

<input id="test1" name="test" type="radio"/>

If it's not does anyone have a better suggestion?

Upvotes: 2

Views: 1719

Answers (5)

Kevin Suttle
Kevin Suttle

Reputation: 8489

It sounds like you're trying to replicate a fieldset and legend on a per-input basis.

What you probably want is aria-describedby.

<label for="emailInput" id="email-address-label" aria-describedby="email-address-label-description">Email</label>
<span class="label-description" id="email-address-label-description">This will also be your login username</span>
<input type="email" id="emailInput" autocapitalize="none" spellcheck="off" autocomplete="email" inputmode="email" />

Upvotes: 1

SebHallin
SebHallin

Reputation: 891

This link should describe to you why you shouldn't write like that.

You could use <span class="labelHead"></span> <span class="labelDescription"></span> inside the label-tag, but I wouldn't recommend it.

The best would be to write <h3>...</h3><label for="...">...</label><input...

Except for screen-readers, robots and similar, the for attribute is only used to make the text clickable to get focus on the input field, right?

Upvotes: 0

Siguza
Siguza

Reputation: 23900

Pasting the following code in the W3 HTML Validator yields two errors

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
    </head>
    <body>
        <label for="test1">
            <h3>Label Heading</h3>
            <p>Label Description</p>
        </label>
        <input id="test1" name="test" type="radio"/>
    </body>
</html>

Element h3 not allowed as child of element label in this context.

Element p not allowed as child of element label in this context.

So this code is rather invalid.

I would also say that is semantically "invalid" (or at least weird), because I think of a label as a description for the input box, and a heading does not fit there.

Upvotes: 6

Shariq Ansari
Shariq Ansari

Reputation: 4641

As per W3c they suggest not to use a block element inside a inline element. As label is inline element and Headings and paragraphs are block elements.

Upvotes: 1

Bladepianist
Bladepianist

Reputation: 490

If you're trying to validate your HTML/CSS and others code, there's a great and official website for it :

W3C Validator

You can check just by specifying your website address or copy-paste the source-code.

Beyond the preferences of each person, you'll have the assurance to get tested by the "ruler" (Don't know how to say it) when talking about WWW.

Upvotes: 0

Related Questions