问题
I'm trying to adjust the position of several sibling divs based on which sibling they are. Currently, they're all position: absolute
, but that's not set in stone.
They are each a few hundred pixels tall, but I want them to overlap each other so that the ones behind only 'peek' out above the ones in front by a few pixels. The easiest way I can think of to do this would be a Less mixin for nth-of-type
that, instead of only applying the rules to the matching one index, instead passes the index into the mixin. Basically, I want this:
&:nth-of-type(@n) {
top: @n * 20px;
}
Edit: what I'm currently doing:
&: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);
}
Obviously this is nonoptimal. Is there a better way to do this in Less?
Alternatively, is there a CSS field for something like 'layout-height'
that would give the div a certain height (not its full height) in the layout?
回答1:
Assuming you know the number of elements in advance (or are recalculating your css on the fly somehow), then essentially what you have works if put into a loop structure which I originally discovered here on stack overflow.
LESS Code
.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);
}
Outputs
.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;
}
回答2:
I don't see a way that this is possible. Would be pretty cool, but I guess that's what javascript is for.
$('.parentDiv').children('div').each(function() {
$(this).css({"top": num * 20 + "px"});
num = num + 1;
});
Here's the full js solution: http://jsfiddle.net/VbuQ9/
You can play around with the LESS fiddle here if you want. http://jsfiddle.net/hV8sX/1/
来源:https://stackoverflow.com/questions/13554978/less-mixin-or-selector-to-change-position-based-on-sibling-index