Caner
Caner

Reputation: 59238

jQuery: Center text inside progress bar

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
});

Upvotes: 8

Views: 7461

Answers (3)

Chris Baker
Chris Baker

Reputation: 50602

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

Upvotes: 1

Caner
Caner

Reputation: 59238

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
});

Upvotes: 3

adeneo
adeneo

Reputation: 318302

You'll need a line-height to get it centered vertically:

line-height: 35px;

FIDDLE

Upvotes: 2

Related Questions