13

I can't believe I'm having to ask this, but I'm at my wit's end.

I'm trying to display 2 form fields inline, but with the label for each field on the top. In ascii art:

Label 1      Label 2
---------    ---------
|       |    |       |
---------    ---------

Should be pretty simple.

<label for=foo>Label 1</label>
<input type=text name=foo id=foo />

<label for=bar>Label 2</label>
<input type=text name=bar id=bar />

This will get me:

        ---------           ---------
Label 1 |       |   Label 2 |       |
        ---------           ---------

To get the labels on top of the boxes, I add display=block:

<label for=foo style="display:block">Label 1</label>
<input type=text name=foo id=foo />

<label for=bar  style="display:block">Label 2</label>
<input type=text name=bar id=bar />

After I do this, the labels are where I want them, but the form fields are no longer inline:

Label 1  
---------
|       |
---------

Label 2  
---------
|       |
---------

I've been unable to find a way to wrap my html so the fields display inline. Can anyone help?

rcourtna
  • 4,589
  • 5
  • 26
  • 27

2 Answers2

34

I would put each input inside an span with display:inline-block, like this:

<span style="display:inline-block">
    <label for=foo style="display:block">Label 1</label>
    <input type=text name=foo id=foo />
</span>

<span style="display:inline-block">
    <label for=bar  style="display:block">Label 2</label>
    <input type=text name=bar id=bar />
</span>
Raugturi
  • 585
  • 5
  • 11
19

EDIT:

The original answer has not aged well since 2010. Placing inputs within labels used to be a common practice back then in order to avoid creating additional DOM elements for styling.

As web development for accessibility (a11y) compliance has matured since, (And as @CrandellWS points out in the comments below) the general consensus is that @Raugturi's answer is more appropriate now.


ORIGINAL ANSWER:

You could enclose your inputs in with the labels and then use CSS:

label{display:inline-block;}
input{display:block;}
<label>Label 1<input type=text name=foo id=foo /></label>
<label>Label 2<input type=text name=bar id=bar /></label>
edl
  • 3,194
  • 22
  • 23
  • This works too. It was display:inline-block that was key to solving the problem. Thanks! – rcourtna Jun 16 '10 at 14:26
  • Nice answer thanks. I was looking for a generic solution that would let me display the labels on top *only* for some inputs. It doesn't make sense for checkbox or radios... – Adrián Apr 26 '14 at 21:09
  • 1
    One might ask [Should I put input tag inside label tag?](http://stackoverflow.com/q/774054/1815624) – CrandellWS Sep 22 '15 at 20:47