Consider the following code:
HTML:
<div>
<label for='name'>Name:</label>
<input type='text' id='name' />
</div>
CSS:
div {
height: 50px;
border: 1px solid blue;
}
What would be the easiest method to put the label
and the input
in the middle of the div
(vertically) ?
This question is related to
css
html
vertical-alignment
Use padding
on the div
(top and bottom) and vertical-align:middle
on the label
and input
.
example at http://jsfiddle.net/VLFeV/1/
This works cross-browser, provides more accessibility and comes with less markup. ditch the div. Wrap the label
label{
display: block;
height: 35px;
line-height: 35px;
border: 1px solid #000;
}
input{margin-top:15px; height:20px}
<label for="name">Name: <input type="text" id="name" /></label>
I'm aware this question was asked over two years ago, but for any recent viewers, here's an alternative solution, which has a few advantages over Marc-François's solution:
div {
height: 50px;
border: 1px solid blue;
line-height: 50px;
}
Here we simply only add a line-height
equal to that of the height of the div. The advantage being you can now change the display property of the div as you see fit, to inline-block
for instance, and it's contents will remain vertically centered. The accepted solution requires you treat the div as a table cell. This should work perfectly, cross-browser.
The only other advantage being it's just one more CSS rule instead of two :)
Cheers!
You can use display: table-cell
property as in the following code:
div {
height: 100%;
display: table-cell;
vertical-align: middle;
}
Wrap the label and input in another div with a defined height. This may not work in IE versions lower than 8.
position:absolute;
top:0; bottom:0; left:0; right:0;
margin:auto;
a more modern approach would be to use css flex-box.
div {_x000D_
height: 50px;_x000D_
background: grey;_x000D_
display: flex;_x000D_
align-items: center_x000D_
}
_x000D_
<div>_x000D_
<label for='name'>Name:</label>_x000D_
<input type='text' id='name' />_x000D_
</div>
_x000D_
a more complex example... if you have multible elements in the flex flow, you can use align-self to align single elements differently to the specified align...
div {_x000D_
display: flex;_x000D_
align-items: center_x000D_
}_x000D_
_x000D_
* {_x000D_
margin: 10px_x000D_
}_x000D_
_x000D_
label {_x000D_
align-self: flex-start_x000D_
}
_x000D_
<div>_x000D_
<img src="https://de.gravatar.com/userimage/95932142/195b7f5651ad2d4662c3c0e0dccd003b.png?size=50" />_x000D_
<label>Text</label>_x000D_
<input placeholder="Text" type="text" />_x000D_
</div>
_x000D_
its also super easy to center horizontally and vertically:
div {_x000D_
position:absolute;_x000D_
top:0;left:0;right:0;bottom:0;_x000D_
background: grey;_x000D_
display: flex;_x000D_
align-items: center;_x000D_
justify-content:center_x000D_
}
_x000D_
<div>_x000D_
<label for='name'>Name:</label>_x000D_
<input type='text' id='name' />_x000D_
</div>
_x000D_
Source: Stackoverflow.com