Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

less mixin or selector to change position based on sibling index?

Tags:

html

css

less

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?

like image 416
Will Whitney Avatar asked Nov 25 '12 20:11

Will Whitney


1 Answers

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;
}
like image 197
ScottS Avatar answered Nov 16 '22 16:11

ScottS