sbrbot sbrbot - 4 months ago 11
HTML Question

Positioning form elements and their labels in row

How to position input form elements with their labels like this but not using table? Labels should be centered above input elements and blocks in row should be centered within outer block.

+----------------------------------------------+
| label1 label2 label3 |
| [..........] [..........] [..........] |
+----------------------------------------------+


There could be 1, 2, 3 or more elements in the same row.

I tried this:

<style>
.outer{text-align:center;}
.inner{float:left;}
</style>

<form>
<div class="outer">
<div class="inner">
<label name="l1">label1</label><br><input id="l1" name="label1">
</div>
<div class="inner">
<label name="l2">label2</label><br><input id="l2" name="label2">
</div>
<div class="inner">
<label name="l3">label3</label><br><input id="l3" name="label3">
</div>
</div>
</form>

Answer

Place them in the same div, and center the text in that div:

.wrapper {
  text-align:center;
}

.wrapper * {
  text-align:left;
}

.okay {
  display:inline-block;
}

.okay p {
  text-align:center;
}
<div class="wrapper">
 <div class="okay">
  <p>text</p>
  <input type='text'>
 </div>
 <div class="okay">
  <p>text</p>
  <input type='text'>
 </div>
 <div class="okay">
  <p>text</p>
  <input type='text'>
 </div>
</div>