8

我正在尝试根据它们是哪个兄弟来调整几个兄弟 div 的位置。目前,它们都是position: absolute,但这并不是一成不变的。

它们每个都有几百像素高,但我希望它们相互重叠,以便后面的那些只能“窥视”前面的几个像素。我能想到的最简单的方法是为此使用 Less mixin nth-of-type,而不是仅将规则应用于匹配的一个索引,而是将索引传递给 mixin。基本上,我想要这个:

&:nth-of-type(@n) {
    top: @n * 20px;
}

编辑:我目前在做什么:

&:nth-of-type(1) {
    .card_offset(1);
}
&:nth-of-type(2) {
    .card_offset(2);
}
&:nth-of-type(3) {
    .card_offset(3);
}
&:nth-of-type(4) {
    .card_offset(4);
}

显然这是非最优的。有没有更好的方法来做到这一点?

或者,是否有一个 CSS 字段'layout-height'可以让 div 在布局中具有一定的高度(而不是其全高)?

4

2 回答 2

10

假设您事先知道元素的数量(或者正在以某种方式重新计算您的 css),那么如果放入我最初在 stack overflow 上发现的循环结构中,那么基本上您所拥有的工作。

更少的代码

.loop(@index) when (@index > 0) {
     //set top amount
    &:nth-of-type(@{index}) { //NOTE: 1.3.3 and under is just @index, not @{index}
        top: @index * 20px;
    }

     // next iteration
     .loop(@index - 1);
}

// end the loop when index is 0
.loop(0) {}

.yourElem {
    @n: 6; //num of elements (could skip this and just put number in)
    .loop(@n);
}

输出

.yourElem:nth-of-type(6) {
  top: 120px;
}
.yourElem:nth-of-type(5) {
  top: 100px;
}
.yourElem:nth-of-type(4) {
  top: 80px;
}
.yourElem:nth-of-type(3) {
  top: 60px;
}
.yourElem:nth-of-type(2) {
  top: 40px;
}
.yourElem:nth-of-type(1) {
  top: 20px;
}
于 2012-11-25T20:50:53.213 回答
0

我不认为这是可能的。会很酷,但我想这就是javascript的用途。

$('.parentDiv').children('div').each(function() {
    $(this).css({"top": num * 20 + "px"});
    num = num + 1;
});

这是完整的 js 解决方案:http: //jsfiddle.net/VbuQ9/

如果你愿意,你可以在这里玩 LESS fiddle。 http://jsfiddle.net/hV8sX/1/

于 2012-11-25T21:10:49.213 回答