将绝对div放在彼此相同的距离上

时间:2016-09-03 09:54:59

标签: javascript jquery html css

我有一个相对定位的容器,里面有许多绝对定位的div。我需要使用CSS' left'将内部div放在彼此相同距离的位置。属性。

我可以通过为每个人设置固定的左值来实现,但更喜欢使用一个函数来计算它,而不管有多少内部div。

因此,所需的结果如下图所示,后面是我现在的代码。基本上我只是坚持计算:)

提前感谢您的帮助。

enter image description here

HTML

<div id="bubbles-container" populate-bubbles></div>

CSS

#bubbles-container{
   position: relative;
   width: 100%;
   height: 300px;
}
.bubble {
   position: absolute;
   border: 1px solid rgba(0, 0, 0, 0.2);
   bottom: 0;
   border-radius: 10px;
   height: 15px;
   width: 15px;
}

JS /角

app.directive('populateBubbles', [function(){
    return function(scope, element, attr){
        console.log(element);
        for (i = 1; i <= 10; i++){
            element.append('<div class="bubble bubble' + i + '"></div>');
        }

        element.find('.bubble').each(function(){
            var bubbleLength = $(this).length;
            var bubbleWidth = $(this).width();
            var containerWidth = element.width();

            ...
        })
    }
}])

3 个答案:

答案 0 :(得分:3)

不要用绝对位置打扰你,使用flex。你不必计算:

#bubbles {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

看看这个 - &gt; https://jsbin.com/gepufuy/1/edit?html,css,js,output

答案 1 :(得分:1)

如果你真的不能使用flexbox,这是另一个使用

的解决方案
display: table;
display: table-cell;

哪个与IE10兼容。
- &GT; https://jsbin.com/gepufuy/6/edit?html,css,js,output

答案 2 :(得分:0)

使用jQuery,您可以尝试这样的事情:

var i = 0;
var container_width = $('#bubbles-container').width();
var bubble_number = $('.bubble').length;

$('.bubble').each(function() {

    var left_space = (container_width / bubble_number) * i;
    $(this).css({left: left_space + 'px'});

    i++;
});
相关问题