Stretch elements to fit a container

I'm writing a form layout with this look (using Bootstrap, but I don't think that's relevant for my question):

+-----------------container------------------+
|                                            |
|  label1    [ input ]    label2   [ input ] |
|  label3    [ input ]    label4   [ input ] |
|  label5    [ input ]    label6   [ input ] |
|                                            |
+--------------------------------------------+

The [input] elements are fixed size. I need the two columns of labels to be correctly aligned, but I do not want them to be the same width. In other words, I nead the labels to expand to the widest label of that column.

Is it possible to do?

This is more or less the HTML i'm using:

<div id="whatever">
<form>
  <div class="controls controls-row">
    <label for="input1">label1</label>
    <input class="span2" type="text" id="input1">
    <label for="input2">label2</label>
    <input class="span2" type="text" id="input2">
  </div>
  <div class="controls controls-row">
    <label for="input3">label3</label>
    <input class="span2" type="text" id="input3">
    <label for="input4">label4</label>
    <input class="span4" type="text" id="input4">
  </div>
</form>
</div>

Upvotes: 0

Views: 624

Answers (2)

Rain Diao
Rain Diao

Reputation: 926

display: table, and table-cell could work.

column is also an option, but less compatible. (@Sirko shown a great demo.)

css

form {
    display:table;
}

.controls-row {
    display: table-row;
}

.controls-row > label,
.controls-row > input {
    display: table-cell;
}

jsFiddle demo: http://jsfiddle.net/Mxx4M/

Upvotes: 1

Sirko
Sirko

Reputation: 74046

You could try column-count (browser-compatibility). Your HTML would have to change to something like this:

<div id="whatever">
<form>
  <div class="controls controls-row">
    <label for="input1">label1</label>
    <input class="span2" type="text" id="input1">
  </div>
  <div class="controls controls-row">
    <label for="input2">label2</label>
    <input class="span2" type="text" id="input2">
  </div>
  <div class="controls controls-row">
    <label for="input3">label3</label>
    <input class="span2" type="text" id="input3">
  </div>
  <div class="controls controls-row">
    <label for="input4">label4</label>
    <input class="span4" type="text" id="input4">
  </div>
</form>
</div>

and then apply the following CSS:

#whatever { 
  -moz-column-count: 2; 
  -webkit-column-count: 2; 
  column-count: 2; 
}
.controls-row { white-space: nowrap; }

The second CSS-rule prevents line-breaks within a input-label row.

Upvotes: 1

Related Questions