css模仿一个简单的条形图

时间:2017-11-02 14:37:31

标签: css css3 flexbox

我正在尝试用css创建它,并且很难让它正确对齐。我只是想填充一个从div的中间点开始并且其高度等于百分比的方框。如果它超过一定百分比,我希望它在填充的div中。猜测这并不难,但我似乎无法弄明白。主要是如何让填充盒从中间开始下降并根据正面或负面填充或填充。

我将不胜感激任何帮助。

enter image description here

jsbin链接

http://jsbin.com/lexifetuja/edit?html,css,js,output

.col-sm-3 {
  border: 1px solid #000;
  height:200px;
}

.fill-box {
    background-color: #213F5E;
  width:100%;
  position: absolute;
  top: 50%
}

.fill-box1 {
    height: 6%;
}

.fill-box2 {
    height: 41%;
}

<div class="container">
    <div class="row">
        <div class="col-sm-3">
            <span class="percentage text-left">12%</span>

            <div class="fill-box fill-box1"></div>
        </div>

        <div class="col-sm-3">
            <span class="percentage text-left">-82%</span>

            <div class="fill-box fill-box2"></div>
        </div>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

您可以为负百分比fill-box元素添加一个类,并将top位置设置为100px(以便元素的顶部从容器的中间点开始)然后对于正数百分比fill-box,只需将top位置设为负值,即剩余百分比:

.col-sm-3 {
  border: 1px solid #000;
  height:200px;
}

.fill-box {
  background-color:#213F5E;
  width:100%;
  position:absolute;
  top:50%;
  left:0;
}
  .fill-box.negative {
    top:100px;
  }

.fill-box1 {
  height:6%;
  transform:translateY(-94%);
}

.fill-box2 {
  height:41%;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
    <div class="row">
        <div class="col-sm-3">
            <span class="percentage text-left">12%</span>

            <div class="fill-box fill-box1"></div>
        </div>

        <div class="col-sm-3">
            <span class="percentage text-left">-82%</span>

            <div class="fill-box fill-box2 negative"></div>
        </div>
    </div>
</div>