Align labels in form next to input
WARNING: OUTDATED ANSWER
Nowadays you should definitely avoid using fixed widths. You could use flexbox or CSS grid to come up with a responsive solution. See the other answers.
One possible solution:
- Give the labels
display: inline-block
; - Give them a fixed width
- Align text to the right
That is:
label {
display: inline-block;
width: 140px;
text-align: right;
}
<div class="block">
<label>Simple label</label>
<input type="text" />
</div>
<div class="block">
<label>Label with more text</label>
<input type="text" />
</div>
<div class="block">
<label>Short</label>
<input type="text" />
</div>
JSFiddle
While the solutions here are workable, more recent technology has made for what I think is a better solution. CSS Grid Layout allows us to structure a more elegant solution.
The CSS below provides a 2-column "settings" structure, where the first column is expected to be a right-aligned label, followed by some content in the second column. More complicated content can be presented in the second column by wrapping it in a <div>.
[As a side-note: I use CSS to add the ':' that trails each label, as this is a stylistic element - my preference.]
/* CSS */
div.settings {
display:grid;
grid-template-columns: max-content max-content;
grid-gap:5px;
}
div.settings label { text-align:right; }
div.settings label:after { content: ":"; }
<!-- HTML -->
<div class="settings">
<label>Label #1</label>
<input type="text" />
<label>Long Label #2</label>
<span>Display content</span>
<label>Label #3</label>
<input type="text" />
</div>