Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I Want my Label to Vertically Align With my Input Field

Here is what my work is so far:

http://jsfiddle.net/2RCBQ/

<div id="main">
<form>
    <label>First Name:<input type="text" id="firstname"></label><br/>
    <label>Last Name:<input type="text" id="lastname"></label><br>
    <label>E-Mail:<input type="text" id="email"></label><br/>
    <label>Phone:<input type="text" id="phone"></label><br/>
</form>
</div>

CSS

#main {
    width:300px;

}  

#main input {
    float:right;
    display:inline;
}

#main label {
    color: #2D2D2D;
    font-size: 15px;
    width:250px;
    display: block;
}

Currently, the label (on the left) is kind of towards to top of the input field (on the right). I want to vertically align them so the label since in the middle of the input field.

I've tried vertical-align and it does not work. Please help me try to figure out the problem. Thanks.

like image 201
James Mitchell Avatar asked Mar 04 '13 02:03

James Mitchell


People also ask

How do you vertically align a label in HTML?

How to center text vertically in a regular label control. The CSS tag vertical-align does not work but there is a work-around of sorts...for some reason padding-top seems to work. So you can set a value for the padding-top and then adjust the height of your label to get the text where you want it to be.

How do you align inputs and labels in HTML?

We specify the margin-bottom of our <div> element. Then, we set the display of the <label> element to "inline-block" and give a fixed width. After that, set the text-align property to "right", and the labels will be aligned with the inputs on the right side.


1 Answers

I feel nesting <span> adds a lot of unnecessary markup.

display: inline-block lets the <label> and <input> sit next to each other just like with float: right but without breaking document flow. Plus it's much more flexible and allows more control over alignment if you (or the user's screen reader) want to change the font-size.

Edit: jsfiddle

label, input {
    display: inline-block;
    vertical-align: baseline;
    width: 125px;
}

label {
    color: #2D2D2D;
    font-size: 15px;
}

form, input {
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
}

form {
    width: 300px;
}
<form>
    <label for="firstname">First Name:</label><input type="text" id="firstname">
    <label for="lastname">Last Name:</label><input type="text" id="lastname">
    <label for="email">E-Mail:</label><input type="text" id="email">
    <label for="phone">Phone:</label><input type="text" id="phone">
</form>
like image 139
thgaskell Avatar answered Sep 23 '22 04:09

thgaskell