8

I'm trying to have a fluid input box with 100% width, while having the label floated to the left. Here's what I currently have:

.left {
  float: left;
}

input {
  width: 100%;
}

<form>
    <label class="left">Name:</label>
    <input class="left" id="name" name="name"/>
    <div class="clear"></div>
</form>

This works, however it drops down below the label. If I use a parent div to assign the floats, then it doesn't span 100%. Any ideas?

Thank you!

kefir500
  • 4,184
  • 6
  • 42
  • 48
dzm
  • 22,844
  • 47
  • 146
  • 226
  • 3
    What are you trying to do? Are you trying to get the input box and the label on the same line? If you have an input box of 100% the container's width, there's no room for a label on that same line, so it would be impossible to do so. – Will Jul 15 '11 at 21:42

2 Answers2

23

See: http://jsfiddle.net/r2769/ (resize the window)

CSS:

.left {
    float: left;
}

.left2 {
    overflow: hidden;
    display: block;
    padding: 0 4px 0 10px
}
.left2 input {
    width: 100%
}

HTML:

<form>
    <label class="left" for="name">Name:</label>
    <span class="left2"><input id="name" name="name" /></span>
</form>

An explanation of the method is here.

Serp C
  • 864
  • 1
  • 10
  • 24
thirtydot
  • 224,678
  • 48
  • 389
  • 349
  • Yeah, it's really very useful :) – thirtydot Jul 15 '11 at 21:50
  • Thx for the smart idea illustrated on a nice jsfiddle. – chikamichi Jan 31 '13 at 02:33
  • Do you know how to do this the other way around, with the text on the right? Bit trickier than it seems. – mpen Sep 13 '16 at 21:40
  • 1
    @mpen: http://stackoverflow.com/questions/6938900/how-can-i-put-an-input-element-on-the-same-line-as-its-label/6938990#6938990 / http://jsfiddle.net/thirtydot/Khmhk/782/. I usually use `display: table` for this now. Can also do it with flexbox. – thirtydot Sep 14 '16 at 07:41
  • @thirtydot Cool. I used the table variant. Thanks! – mpen Sep 14 '16 at 18:51
3

I recently found out about calc in css:

width: calc(100% - 100px);

this can be used to solve this problem: jsfiddle here

HTML:

<div class="setting">
    label
    <input class="s2"/>
</div>

CSS:

.setting {
    position: relative;
    width: 100%;
}
.setting .s2 {
    position: absolute;
    left: 180px;
    width: calc(100% - 184px);
}
jvilhena
  • 1,131
  • 8
  • 21
  • works, but not supported across all modern browsers (3 versions back). Breaks, most notably in Safari 5 – Graham T Jun 26 '14 at 20:01