在水平条形图中排列基于百分比的div



我正在尝试创建一个水平HTML条形图,并有一些问题围绕布局包装我的头。基本上,我想有一个div的背景图像,有10条均匀间距的竖线,然后在该div中有几个div,宽度基于百分比。

功能上,一切都如预期的那样工作,但是我有一个困难的时间弄清楚如何让条形图与背景图像中的竖线对齐。

例如,如果一个条的宽度为60%,它应该与第6条垂直线对齐。

HTML:

<div class="chart">
    <div class="bar-container">
        <div data-percentage="70" class="bar">Product 1</div>
        <div data-percentage="30" class="bar">Product 2</div>
        <div data-percentage="90" class="bar">Product 3</div>
    </div>
</div>
CSS:

.chart {
    width:320px;
    height:200px;
    background-image:url('http://s15.postimg.org/ku83p3fvf/bars.png');
    background-repeat:no-repeat;
    background-size:contain;
    position: relative;
}
    .chart .bar-container {
        position:absolute;
        bottom:30px;
        width:100%;
    }
        .chart .bar-container .bar {
            background:#55565a;
            margin-top:5px;
            color:#fff;
            font-size:16px;
            padding:2px 0;
        }
Javascript:

$('.bar').each(function() {
    percentage = $(this).attr('data-percentage');
    $(this).css('width',percentage+'%');
});

JSFiddle

你知道我忽略了什么吗?

你有你的背景图像划分为9条,而不是10条。因此,您必须做一些计算以使宽度匹配。或者,您可以将图像设置为10条而不是9条。这是一个固定的JSFiddle,注意Jquery部分

中的数学运算
$('.bar').each(function() {
    percentage = $(this).attr('data-percentage');
    $(this).css('width',percentage / .9 +'%');
});

最新更新