Brained Washed
Brained Washed

Reputation: 703

How can I add label inside a progress bar tag?

I want to add a label in my progress bar tag like in this beautiful example:

enter image description here

Assuming the blue is the value and the red is the max, how can I add a label inside there like my "35"?

Upvotes: 20

Views: 16056

Answers (2)

user2536988
user2536988

Reputation: 31

I attempted to do this myself and finally came across a workaround.

Using the pseudo element :before you can do it a different way

You use content: attr(value) like this: https://jsfiddle.net/96z0gwv7/1/ - more CSS styling on link

progress
{
  text-align:center;
}

progress:before {
  content: 'Value is ' attr(value);
}

<progress value="6" max="10"></progress>
<progress value="9" max="10"></progress>

If you're not wanting the same text format each time then you could use the data attribute (i.e data-label)

.unique:before {
   content: attr(data-label);
}

<progress class="unique" value="9" max="10" data-label="90% completed"></progress>
<progress class="unique" value="0" max="10" data-label="About to begin"></progress>

Upvotes: 3

Philip Whitehouse
Philip Whitehouse

Reputation: 4157

Use CSS's position:relative to manoeuvre the text onto the bar.

A quick and dirty solution for a short bar is:

position: relative;
left: -100px;

where left forces the text that would be next to the bar on top of it.

In the comments, Matthias made the point that left doesn't work if the progress bar is 100% width.

It doesn't work because it forces the text below the bar. It'll fail for any width of bar sufficient to force the text below.

Instead you have to get a bit more clever and do something like:

    position: relative;
    top: -1.5em;
    margin-left: 50%;

Here the top:-1.5em replaces the left adjustment in the jsFiddle. The margin-left is an attempt to centre the text. It should actually be a little less than 50%.

If someone has a better solution to centre the text on the bar that's less hacky than the hand-wavy 50%ish margin feel free to comment on it and I'll adjust this again.

Upvotes: 5

Related Questions