使用flexbox时如何叠加两个div?

时间:2019-02-22 03:05:13

标签: html css flexbox

我正在使用父级div,它是一个flexbox。在其中,我需要两个子div,每个子div都跨越父div的整个宽度(宽度:100%),以便它们彼此重叠(重叠)。这样,当您更改一个子div的宽度时,不应以任何方式重新放置另一个子div的位置。

例如:我正在尝试创建如下所示的进度条: enter image description here

为此,我使用两个div-外部div(灰色背景)呈现进度条的轮廓,内部div(绿色背景)显示进度。我还要求在中间显示数字百分比(81%)。内部div(绿色bg)宽度值会根据数字百分比保持警惕。无论进度如何(内部div宽度),数字百分比都应始终位于OUTER DIV的中心。

您能告诉我如何实现吗?谢谢。

3 个答案:

答案 0 :(得分:1)

对于样式基本进度条,您可以使用position: absolute覆盖项目。

您可以使用flexbox进行定位,但是只需在中间文本(例如“ 80%”)上使用position: absolute和后续规则,您将使用更少的代码行,同时启用叠加需求和居中功能。

要(动态)控制进度条,请使用Javascript。您将按照 something 的进度在JS中构建一些逻辑,然后相应地更新栏的CSS规则。没有JS,就无法做到这一点。

如果只需要一个带有运动的虚拟进度条,则可以使用CSS动画规则在不使用JS的情况下对其进行动画处理。

Codepen

#container {
  position: relative;
  width: 400px;
  height: 40px;
  background-color: grey;
  border: 2px solid black;
}

#text {
    position: absolute;
    top: 50%;  
    left: 50%;
    transform: translate(-50%,-50%); 
}

#fill {
  background-color: green;
  width: 80%;
  height: 100%;
}
<div id="container">
  <div id="text">80%</div>
  <div id="fill">&nbsp;</div>
</div>

答案 1 :(得分:0)

不确定我是否了解...您想要实现这种目标吗?

HTML

<section class="parent">
  <article class="child">
  </article>
  <article class="child">
  </article>
</section>

CSS

.parent {
  display: flex;
  width: 100vw;
  justify-content: space-around;
}

.child {
  width: 50%;
  height: 60px;
}

Link to codePen

答案 2 :(得分:0)

不需要flexbox或任何复杂的东西,您只需为此使用背景:

.progress {
  width:200px;
  line-height:50px;
  margin:5px;
  text-align:center;
  font-size:30px;
  background:
    linear-gradient(green,green) left no-repeat,
    grey;
}
<div class="progress">
  100%
</div>

<div class="progress" style="background-size:50% 100%">
  50%
</div>

<div class="progress" style="background-size:75% 100%">
  75%
</div>

您可以添加更多的颜色以更接近所需的视觉效果:

.progress {
  width:200px;
  line-height:50px;
  margin:5px;
  text-align:center;
  font-size:30px;
  background:
    /*light overlay on the half top*/
    linear-gradient(rgba(255,255,255,0.3),rgba(255,255,255,0.3)) top/100% 50%,
    /*the two bars*/
    linear-gradient(#539041,#539041) left/5px 100%,
    linear-gradient(#539041,#539041) var(--p,100%) 0/5px 100%,
    /*the progress*/
    linear-gradient(#53e15a,#53e15a) left/var(--p,100%) 100%,
    /*the outer coloration*/
    #bbbbbb;
  background-repeat:no-repeat;
}
<div class="progress">
  100%
</div>

<div class="progress" style="--p:50%">
  50%
</div>

<div class="progress" style="--p:75%">
  75%
</div>