I'm trying to center text vertically & horizontally inside jQuery progress bar. I managed center it horizontally but not vertically. Here is what I have at the moment
My HTML
:
<div id='progressbar'><div id='label'>My text</div></div>
My CSS
:
#progressbar {
width: 80%;
text-align: center;
overflow: hidden;
position: relative;
vertical-align: middle;
}
#label {
float: left;
width: 100%;
height: 100%;
position: absolute;
vertical-align: middle;
}
My JavaScript
:
$("#progressbar").progressbar({
value: 50
});
Managed by adding:
line-height: 200%;
The result: http://jsfiddle.net/GYW73/1/
My HTML
:
<div id='progressbar'><div id='label'>My text</div></div>
My CSS
:
#progressbar {
width: 80%;
text-align: center;
}
#label {
width: 100%;
float: left;
line-height: 200%;
}
My JavaScript
:
$("#progressbar").progressbar({
value: 50
});
You'll need a line-height
to get it centered vertically:
line-height: 35px;
FIDDLE
The vertical-align
style, when applied to block-level elements, seldom behaves the way you might expect it to.
The usage you've shown here works fine... with table cells. It acts like the old and deprecated HTML valign
property. The behavior is different for inline elements, where it acts like the old and deprecated align
HTML property.
When you apply it to box elements (like your div), the browser simply ignores it (see the spec)
Your options for vertical alignment in a block element are limited. You can either:
1) Use line-height to fill the entire vertical space. The browser will vertically align text within its line. The pro of this is that it doesn't require additional wrapping tags, the con is that you must work with a pre-defined height.
2) Use absolute positioning. The advantage of this approach is precision -- you can place the text exactly where you want it. Absolute positioning is pretty intuitive, too. The cons are that you'll need an additional wrapping tag, and you have to work with pre-defined heights.
The only saving grace you have is using percents. You can either use it in the line-height
or as a top
/bottom
in combination with absolute position. Here is a mockup of your same code, using a percent top
to push the div down into the center.
#label {
width: 100%;
top:2.5%;
position:absolute;
}
jsFiddle: http://jsfiddle.net/bLdgN/5/
Documentation
vertical-align
at W3 - http://www.w3.org/wiki/CSS/Properties/vertical-align
vertical-align
at MDN - https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align
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