CSS模仿一个简单的条形图

标签 css 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>

最佳答案

您可以为负百分比 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>

关于CSS模仿一个简单的条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47077946/

相关文章:

jquery - 如何改变jquery mobile页脚的背景颜色?

jquery - 展开 div 内容滚动

html - 如何水平居中此警报?

html - 使用固定导航栏时更正页面导航位置

html - Flex、图片和滚动位置

html - 为什么 flex 元素不缩小过去的内容大小?

javascript - 当元素高度取决于该元素内的文本时,对元素高度进行动画处理

css - 如果父级有列方向,则 Flexbox 基础不起作用

javascript - flex 元素是否有可能与它们上方的元素紧密对齐?

html - 使背景颜色延伸到溢出区域