skyisred
skyisred

Reputation: 7105

CSS gradient: simulate progress bar

enter image description here

Trying to simulate this progress bar using css. It has two backgrounds and one of the backgrounds should only cover a part of the bar, behind the text. The width of it should be easy to manipulate to change the %. I started with the a full bar, but really not sure how add the percentage part to it. Is it possible to do without absolute positioning?

<div class="bar">
    Progress: 60%
</div>

.bar {
    border: 1px solid black;
    color: white;
    display: table-cell;
    width: 250px;
    height: 50px;
    text-align: center;
    vertical-align: middle;        
    background: #003458;
    background: -moz-linear-gradient(top, #003458 0%, #001727 100%);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#003458), color-stop(100%,#001727));
    background: -webkit-linear-gradient(top, #003458 0%,#001727 100%);
    background: -o-linear-gradient(top, #003458 0%,#001727 100%);
    background: -ms-linear-gradient(top, #003458 0%,#001727 100%);
    background: linear-gradient(to bottom, #003458 0%,#001727 100%);
}

Fiddle

Upvotes: 2

Views: 8006

Answers (1)

Linus Caldwell
Linus Caldwell

Reputation: 11058

If you just want to lighten up like your example demonstrates, overlay 2 gradients:

.bar {
    background: linear-gradient(to right, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0.1) 60%, transparent 60%),
                linear-gradient(to bottom, #003458 0%,#001727 100%);
}

Here is a demo. (Removed the vendor prefixes, you should add them again in the final code)


But the problem is, how would you know how large the bar should be? You could create several classes for each value or use JavaScript for this, but of course both solutions are not good. So like others said: Use an inner element:

<div class="bar">
    <p>Progress: 60%</p>
    <span style="width: 60%"></span>
</div>

CSS:

.bar {
    position: relative;
    border: 1px solid black;
    color: white;
    display: block;
    width: 250px;
    text-align: center;
    vertical-align: middle;
    height: 50px;
    line-height: 50px;
    background: linear-gradient(to bottom, #003458 0%,#001727 100%);
}

.bar > span {
    position: absolute;
    display: block;
    top: 0;
    left: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.1);
}

.bar > p {
    display: inline;
    position: relative;
    z-index: 1;
}

With that you can style the value by setting the width within the <span/>'s style attribute. Btw.: I changed the display: table-cell to block and added line-height to vertically center the text. This should work in this case because there is no line break. Besides that, position: relative does nothing on table cells.

Here is a demo.

Upvotes: 5

Related Questions