civiltomain
civiltomain

Reputation: 1166

Can I 'style' and use a label as a 'normal' element

I have discover a way to have an input and label elements as an accordion viewer.

To center vertically my elements I use the label as if it was a div, that is, giving it display:table and create a div inside it. So I have :

<div>
    <input id='myid'>
    <label for ='myid' style='display table'>
        <div style='display:table-cell'>
            <img ....... > 
            thetextforthelabel 
        </div>
    </label>
</div> 

Ok, this works fine.

My question is: am I doing something 'forbiden' ? Can I use the label tag as a container ?

I know that it can be not orthodox .. but It works for me...

Upvotes: 0

Views: 85

Answers (2)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201548

Yes, it is forbidden by the formal rules of HTML. And yes, it works, and the parsing rules of HTML mean that it must work. So this is different from, say, the rule that says that a p element must not contain a div element; that rule is enforced by the parsing process (the p element is implicitly closed when <div> is encountered).

On the other hand, if the content is just an image and text, you don’t need a div element but can use span. In rendering, it does not matter (with the usual CSS caveats) which one you select, since their only difference in rendering is with the default display value, and you are assigning a display value anyway.

<div>
    <input id='myid'>
    <label for ='myid' style='display table'>
        <span style='display:table-cell'>
            <img src="http://lorempixel.com/100/50" alt="(an image)">
            thetextforthelabel 
        </span>
    </label>
</div> 

Upvotes: 1

Oriol
Oriol

Reputation: 288050

Your code is invalid.

The problem is that div elements can only be used

Where flow content is expected.

However, the content model of label elements is

Phrasing content, but with no descendant labelable elements unless it is the element's labeled control, and no descendant label elements.

Anyways, it will probably work, because (unlike e.g. p elements) the end tag of label elements can't be omitted:

Neither tag is omissable

However, I'm not sure of the advantage of having a table element with a single cell. Consider using the following instead:

<div>
    <input id='myid'>
    <label for='myid' style='display:block'>
        <img ....... > 
        thetextforthelabel 
    </label>
</div>

Upvotes: 1

Related Questions