Reputation: 237
Looking for a set of CSS rules that can layout an unknown number of siblings blocks into a staircase formation.
Let's say I have a number of sibling DIV elements within an enclosing one:
<div class="parent">
<div>SIBLING 1</div>
<div>SIBLING 2</div>
...
<div>SIBLING n</div>
</div>
For an arbitrary n
and I wish to have them laid out so that SIBLING 1
has a margin of m
and that SIBLING 2
has margin m+o
for some o
and SIBLING 3
has a margin of m+2o
, until SIBLING n
has a margin of m+o(n-1)
. So the results should look something like this:
SIBLING 1
SIBLING 2
SIBLING 3
...
SIBLING n
In other words the margin (margin-left in this example) increases with each sibling. It is easy to do a rule for each sibling with nth-child but is there a more generic solution?
Upvotes: 4
Views: 3300
Reputation: 87231
For them to be siblings, this is most likely the only option using CSS only (and no float), and since you said in an order of a dozen or so, the CSS will be quite modest.
div {
width: 30px;
height: 20px;
background: lightgray;
text-align: center;
}
div:nth-child(1) { margin-left: 0px; } /* 1st */
div:nth-child(2) { margin-left: 30px; } /* 2nd */
div:nth-child(3) { margin-left: 60px; } /* 3rd */
div:nth-child(4) { margin-left: 90px; } /* 4th */
div:nth-child(5) { margin-left: 120px; } /* 5th */
div:nth-child(6) { margin-left: 150px; } /* 6th */
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
Updated based on a comment.
With a media query and a tiny script this is simple, no framework, just vanilla javascript.
(function(w,d) {
var steps = 30;
w.addEventListener("load", function() {
var divs = d.querySelectorAll('div');
for (var i = 0; i < divs.length; i++) {
divs[i].style.cssText = 'margin-left: ' + (steps * i) + 'px';
}
}, false);
}(window,document));
div {
width: 30px;
height: 20px;
background: lightgray;
text-align: center;
}
@media (max-width: 500px) {
div {
margin-left: 0 !important; /* since the margin is set with inline style,
we need important to override them */
}
}
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
Upvotes: 1
Reputation: 4205
I wrapped every sibling with a .wrapper
div
.
.wrapper > .wrapper {
margin-left: 1em;
}
<div class="parent">
<div class="wrapper">
<div>SIBLING 1</div>
<div class="wrapper">
<div>SIBLING 2</div>
<div class="wrapper">
<div>SIBLING 3</div>
<div class="wrapper">
<div>SIBLING N</div>
</div>
</div>
</div>
</div>
</div>
Upvotes: 1