如何在Bootstrap 3进度条中居中文本?

8
我将尝试使用以下代码展示进度条,该代码与Bootstrap 3相关:

   <div class="progress">
        <div class="progress-bar" style="width: 60%;">
        </div>
        <span>60%</span>
    </div>

输出截图:

屏幕截图

然而,这会导致文字“60%”显示在进度条的右侧,而不是中心。如何使此文本居中,以便它出现在中心位置?

5个回答

21

我会在 span 标签上添加一个类,并将该标签放置在 progress-bar 类之前。然后将 span 设置为 position:absolute 并给进度条设置 text-align:center:

HTML:

<div class="progress">
    <span class="progress-value">60%</span>
    <div class="progress-bar"></div>
</div>

CSS:

.progress {
    text-align:center;
}
.progress-value {
    position:absolute;
    right:0;
    left:0;
}

查看演示:http://jsfiddle.net/bozdoz/fSLdG/2/


出于某种原因,我总是更喜欢定义右和左,而不是宽度...谢谢@Ruddy - bozdoz
1
两个都可以,随意在你的答案中使用我的演示。只是增加了另一个选项。干得好。 - Ruddy

9

补充@bozdoz的答案:

绝对定位进度百分比指示器会解决问题:

HTML

<div class="progress">
    <div class="progress-bar" style="width: 60%;">
    </div>
    <span>60%</span>
</div>

CSS

.progress {
    position:relative;
}
.progress span {
    position:absolute;
    left:0;
    width:100%;
    text-align:center;
    z-index:2;
    color:white;
}

Fiddle: http://jsfiddle.net/Varinder/ejgp5/


1

Twitter的Bootstrap .span类被浮动到了左侧。尝试向添加float:none,它可能会起作用!

.progress span{
   margin: 0px auto;
   float:none;
}

更新:

这肯定可行:HTML

 <div class="progress">
  <div class="bar" style="width: 60%;"></div>
  <span>60%</span>
 </div>

CSS:
 .progress {
    position: relative;
 }

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

 .progress span {
    position: absolute;
    top: 0;
    z-index: 2;
    text-align: center;
    width: 100%;
    color: black;
 } 

0
.progress{ border: 5px solid;}
.progress-bar{background: #369;line-height: 50px;display: inline-block;}
.progress span{display: block; margin: 0px auto; width: 40px; margin-top: -50px; line-height: 50px; color: #fff;}

抱歉,我添加了错误的链接。请检查以下链接:http://jsfiddle.net/VpfkM/1/。 - Moorthy GK

0

试试这个,我用了<center> </center>标签。我不确定它是否向后兼容,但我已在Chrome和Mozilla Firefox中进行了测试,目前没有问题。

示例代码(不需要任何CSS):

<div class="progress progress-striped active" style="margin:0 10%;display:none;" id="uploadProgressbar">
        <center><b><span class="progress-value" id="uploadProgressValue" style="color:red;">00%</span> </b></center>
             <div class="progress-bar progress-bar-primary" role="progressbar" id="uploadProgress" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 0%">

             </div>
</div>

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