【问题标题】:Position bar left within center tag中心标签内左侧的位置栏
【发布时间】:2026-02-10 15:25:01
【问题描述】:

在我的 index.html 中,我创建了以下 div,它位于 center 标记内。

<div class="container">
    <div class="bar">
    <span class="bar-fill"></span>
    </div>
</div>

页面上如下所示:[进度条图片]1

我希望蓝色条位于此容器的左侧。

下面是我的 CSS:

/* Progress Bar */
.container {
width: 400px;
}

.bar {
width: 100%;
background: #eee;
padding: 3px;
border-radius: 3px;
box-shadow: inset 0px 1px 3px rgba(0,0,0,.2);
}

.bar-fill {
height: 20px;
display: block;
background: cornflowerblue;
width: 80%;
border-radius: 3px;
}

再一次,我希望将蓝色条(标有条形或条形填充的 div)定位在容器内的左侧。

谢谢。

【问题讨论】:

  • 请不要使用已弃用的&lt;center&gt; 标签。当您删除它时,问题可能会消失
  • 啊,&lt;center&gt; 标签,我的老朋友。
  • 尝试将 float:left 添加到 .bar-fill
  • 那么在不使用
    标签的情况下,将所有内容居中的最佳方法是什么?
  • 将包含元素的内容的“左”和“右”边距设置为“自动”

标签: javascript html css progress


【解决方案1】:

只需将margin-left: 0px; 添加到.bar-fill

.container {
  width: 400px;
}
.bar {
  width: 100%;
  background: #eee;
  padding: 3px;
  border-radius: 3px;
  box-shadow: inset 0px 1px 3px rgba(0, 0, 0, .2);
}
.bar-fill {
  height: 20px;
  display: block;
  margin-left: 0px;
  background: cornflowerblue;
  width: 80%;
  border-radius: 3px;
}
<div class="container">
  <div class="bar">
    <span class="bar-fill"></span>
  </div>
</div>

【讨论】:

  • 是的,但我也会添加margin: auto;,以防万一。
【解决方案2】:

根据提供的代码,该元素已经留下。

您的 HTML 中没有 center 标记,无论如何,该标记已被弃用,不应再使用。

.container {
  width: 400px;
  margin:auto; /* center the container */
}
.bar {
  width: 100%;
  background: #eee;
  padding: 3px;
  border-radius: 3px;
  box-shadow: inset 0px 1px 3px rgba(0, 0, 0, .2);
}
.bar-fill {
  height: 20px;
  display: block;
  background: cornflowerblue;
  width: 80%;
  border-radius: 3px;
}
<div class="container">
  <div class="bar">
    <span class="bar-fill"></span>
  </div>
</div>

如果容器 div 里面有一个&lt;center&gt;标签,这个标签不能被移除,那么将标签的text-align设置为left应该会有预期的效果。

JSFiddle Demo

【讨论】: