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.
To center both vertically and horizontally, use padding and text-align: center : I am vertically and horizontally centered.
The CSS just sizes the div, vertically center aligns the span by setting the div's line-height equal to its height, and makes the span an inline-block with vertical-align: middle. Then it sets the line-height back to normal for the span, so its contents will flow naturally inside the block.
To get them centered along a line, you'd use vertical-align: middle; . Although note that it centers the text according to its tallest ascender and deepest descender. Each element lines up according to the line you've set, which doesn't change from element to element.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With