如何在 HTML5 进度条中显示数据标签? (跨浏览器)

新手上路,请多包涵

我有一个样式化的 HTML5 进度条,我想在进度条内显示跨浏览器兼容的数据标签。目前显示在进度条上方。

HTML:

 <progress max="100" value="50" data-label="50% Complete"></progress>

CSS:

 progress {
  text-align:center;
  height: 1.5em;
  width: 100%;
  -webkit-appearance: none;
  border: none;
}
progress:before {
  content: attr(data-label);
  font-size: 0.8em;
  vertical-align: 0
}
progress::-webkit-progress-bar {
  background-color: #c9c9c9;
}
progress::-webkit-progress-value,
progress::-moz-progress-bar {
  background-color: #7cc4ff;
}

我得到以下结果,但我想将数据标签 移动 到进度条内:

当前渲染

原文由 user6655274 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 529
2 个回答

TL;DR:不要在 <progress> 元素上使用伪元素。

正如其他答案以及 我在评论中所说,HTML/CSS 进度条是比使用 <progress> 元素更好的解决方案。

基于 Gecko 的浏览器,如 firefox,根本不会显示伪元素。

但是,要回答您的问题,只需将文本放在进度条上:

 progress {
  text-align: center;
  height: 1.5em;
  width: 100%;
  -webkit-appearance: none;
  border: none;

  /* Set the progressbar to relative */
  position:relative;
}
progress:before {
  content: attr(data-label);
  font-size: 0.8em;
  vertical-align: 0;

  /*Position text over the progress bar */
  position:absolute;
  left:0;
  right:0;
}
progress::-webkit-progress-bar {
  background-color: #c9c9c9;
}
progress::-webkit-progress-value {
  background-color: #7cc4ff;
}
progress::-moz-progress-bar {
  background-color: #7cc4ff;
}
 <progress max="100" value="50" data-label="50% Complete"></progress>

请注意,这 没有 很好的浏览器支持(事实上,它非常糟糕),因为 <progress> 是一个 替换元素,例如 <input>

CSS规范对于替换元素是否可以有伪元素并没有完全明确,所以不同的浏览器有不同的渲染。基于 Webkit 的浏览器,例如 Chrome,有时会显示它们。基于 Gecko 的,例如 Firefox,则不会。

在一个有点类似的问题上看到 这个答案

因此,如果这是针对网站,而不是 electron 应用程序或类似应用程序,我 强烈 建议使用 HTML/CSS 进度条:

 .progress {
  height: 1.5em;
  width: 100%;
  background-color: #c9c9c9;
  position: relative;
}
.progress:before {
  content: attr(data-label);
  font-size: 0.8em;
  position: absolute;
  text-align: center;
  top: 5px;
  left: 0;
  right: 0;
}
.progress .value {
  background-color: #7cc4ff;
  display: inline-block;
  height: 100%;
}
 <div class="progress" data-label="50% Complete">
  <span class="value" style="width:50%;"></span>
</div>

注意:即使这是针对带有基于 webkit 的浏览器的应用程序,您仍然不应该在 <progress> 上使用伪元素。正如我上面所说,此功能的规范尚不清楚,将来可能会发生变化,从而破坏您的进度元素。 Webkit 也可能会放弃对此的支持。

我建议只使用 HTML/CSS 进度条,你会在未来省去很多麻烦。

原文由 Jacob G 发布,翻译遵循 CC BY-SA 3.0 许可协议

您需要做的就是将状态文本设置为在状态文本元素上具有 z-index1 (-1 无效,0 是默认值),然后设置负数 margin-top: -32px (对于 height: 32px )你可以保留 progress 元素而不添加任何多余的元素:

 <div style="z-index: 2;"><span>Staging item 144 of 271...</span></div>
<div style="margin-top: -32px;"><progress max="100" value="44">44%</progress></div>

原文由 John 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题