1

I'm trying to make a simple css progress bar for one of my projects; however, it seems the span element is only the width of the text inside of it, even when I set its width. How can I go about this issue, and have it stretch accordingly?

(if words don't do that justice: http://puu.sh/61Zmn.png)

Here's what I got so far:

<html>
<head>
<style>
    .bar {
        padding:0;
        width:300px;
        border:1px solid blue;
        overflow:hidden;
    }

    .bar span {
        padding:0;
        margin:0;
        height:100%;
        color:white;
        text-align:center;
        background-color:red;
        border:1px solid red;
    }
</style>
</head>
<body>
<div class="bar">
    <span style="width:64%;">64%</span>
</div>

1 Answers1

2

It doesn't work because a span is an inline element by default. Change it to an inline-block level element if you want to change the width of it. (example here)

.bar span {
    padding:0;
    margin:0;
    height:100%;
    color:white;
    text-align:center;
    background-color:red;
    border:1px solid red;
    display:inline-block;    /* Added this.. */
}

An inline element's dimensions are defined by the "rendered content within them" - this explains the behavior you are seeing. To achieve the desired results, you would need to use a block level element, as it doesn't exhibit this behavior.

This [width] property does not apply to non-replaced inline elements. The content width of a non-replaced inline element's boxes is that of the rendered content within them (before any relative offset of children). Recall that inline boxes flow into line boxes. The width of line boxes is given by the their containing block, but may be shorted by the presence of floats. - W3 reference

Related to this answer I wrote a while back.

Community
  • 1
  • 1
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304