Reputation: 19723
I am trying to vertically align a SPAN element in the middle of a parent element.
This is what I am doing:
I am trying to get both the username and password labels to be vertically aligned (middle) with the input boxes.
This is my HTML code:
<div class="login_field_wrap">
<span>Username</span>
<input type="text" autocomplete="off" spellcheck="off" id="username" name="username">
<div class="clear"></div>
</div>
This is what I have tried:
.clear { clear:both; }
.login_field_wrap span {
float:left; vertical-align:middle; font-size:13px; color:#333; font-weight:bold; }
.login_field_wrap input {
float:right; vertical-align:middle; padding:8px 5px; border:solid 1px #AAA;
margin:0px; width:250px; }
Vertically aligning an image element inside of this wrapping DIV works absolutely fine, well in Chrome anyway, it just won't align with my SPAN!
Any help would be amazing.
Upvotes: 8
Views: 19785
Reputation: 61
I found the easiest way to do this is to set the parent container display property to table
and the child display property to table-cell
#parent{
display:table;
}
#child{
display:table-cell;
vertical-align:middle;
}
I was able to get this to vertically align an anchor element inside a div.
I put it into the terms of your question in this jsFiddle.
Upvotes: 2
Reputation: 75399
Just remove the float
property from your span class and set it to display:inline-block
and the vertical-align:middle
property will work, like so:
.login_field_wrap span {
color: #333333;
display: inline-block;
font-size: 13px;
font-weight: bold;
text-align: left;
vertical-align: middle;
}
Edit: cleaned up your code a bit, here is a demo that should work across browsers. http://jsfiddle.net/kUe3Y/
Upvotes: 9
Reputation: 11197
I think text-align:center; should work on elements too. If I am not mistaken, that usually works even if not on text.
Upvotes: -4
Reputation: 9173
Vertical aligning via CSS can be tricky, and while CSS3 brings about a slew of goodies to help with that, CSS3 support is lackluster in the current browser market.
To achieve this effect I set the line-height
property of the child element equal to the height of its containing element.
For example, I would use the following CSS:
.login_field_wrap { height:30px; /* or whatever is appropriate for your design */
.login_field_wrap span { height:30px; line-height:30px; }
.login_field_wrap input { height:30px; line-height:30px; }
The only downside of using line-height
to vertically align something is if the text overflows onto a second line, in which case your design will essentially break.
Upvotes: 12
Reputation: 1088
I have never been able to get vertical-align
to work in anything other than <td>s.
A workaround I commonly use would be to define a height for .login_field_wrap
, then set the line-height
property in your <span> to be equal to .login_field_wrap
's height.
Upvotes: 1