Twitter Bootstrap:如何在进度条中居中文本

79

我一直在使用Twitter的Bootstrap,希望进度条上的文本无论值为多少都能居中显示。

以下链接是我现在拥有的。我希望所有文本都与最底部的进度条对齐。

截图如下:

progress bar

我已经尝试过使用纯CSS来解决问题,并且正在尽可能避免使用JS,但如果这是最清晰的解决方法,我也愿意接受它。

<div class="progress">
    <div class="bar" style="width: 86%">517/600</div>
</div>
2个回答

198

Bootstrap 5:(与 v4x 相同)

<div class="progress position-relative">
    <div class="progress-bar" role="progressbar" style="width: 60%" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100"></div>
    <small class="justify-content-center d-flex position-absolute w-100">60% complete</small>
</div>
使用实用类的Bootstrap 4:(感谢MaPePeR的贡献)
<div class="progress position-relative">
    <div class="progress-bar" role="progressbar" style="width: 60%" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100"></div>
    <small class="justify-content-center d-flex position-absolute w-100">60% complete</small>
</div>

Bootstrap 3:

Bootstrap现在支持进度条中span元素内的文本。HTML与Bootstrap示例相同。(请注意,类sr-only已被删除)

HTML:

<div class="progress">
    <div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%;">
        <span>60% Complete</span>
    </div>
</div>

...然而,它只会将文字居中于进度条本身,因此我们需要一些自定义CSS。

将以下内容粘贴到另一个样式表/加载Bootstrap CSS的位置下面:

CSS:

/**
 * Progress bars with centered text
 */

.progress {
    position: relative;
}

.progress span {
    position: absolute;
    display: block;
    width: 100%;
    color: black;
 }

JsBin文件:http://jsbin.com/IBOwEPog/1/edit


Bootstrap 2:

将以下内容粘贴到另一个样式表中,或者在加载Bootstrap的CSS之下:

/**
 * Progress bars with centered text
 */
.progress {
    position: relative;
}

.progress .bar {
    z-index: 1;
    position: absolute;
}

.progress span {
    position: absolute;
    top: 0;
    z-index: 2;
    color: black; /* Change according to needs */
    text-align: center;
    width: 100%;
}

然后通过在.bar外添加一个span元素来向进度条添加文本:

<div class="progress">
    <div class="bar" style="width: 50%"></div>
    <span>Add your text here</span>
</div>

JsBin:http://jsbin.com/apufux/2/edit


1
感谢提供详细信息。小修正:即使是Bootstrap 3,您也应该有“.progress {position: relative;}”。如果没有这个,如果您的进度条在一个div中,它将不会尊重div的宽度。(1) 没有进度位置相对jsbin (2) 有进度位置相对jsbin - Amir
1
谢谢,Amir。我会把这个加到说明里。 - Thomas Maurstad Larsson
1
仅适用于Bootstrap 2的示例仅在我将span放在div [class = bar]之前才起作用。否则,根据填充的百分比,该span会被推到右侧。 - user1226868
文本颜色的解决方案 https://dev59.com/bGoy5IYBdhLWcg3wBJkx - Oleg
2
我刚刚尝试了使用Bootstrap 4.5,发现我需要在<small>类属性中添加mt-2,否则文本不会居中。 - D. Foley
显示剩余3条评论

3

以下是Bootstrap 3的答案,如Bootstrap示例所示

<div class="progress text-center">
  <div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%;">
    <span>60% Complete</span>
  </div>
    <span>40% Left</span>
</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接