0

I want to have a series of elements, and I want to have incremental background colors, but I also want to not hard-code it in order to allow for future expansion.

<div class="container">
    <div>one</div>
    <div>two</div>
    <div>three</div>
</div>

I could do something like this:

.container div:nth-child(0) {
    background-color: #0000ff;
}
.container div:nth-child(1) {
    background-color: #000066;
}
.container div:nth-child(2) {
    background-color: #000000;
}

I would rather do that with a single rule, which would allow more succinct code and also allow for more extensibility (for, say, 6 elements). Is this even possible? I am aware that something like this is pretty straightforward with JQuery, but I would rather just use CSS if possible.

polson136
  • 151
  • 1
  • 10
  • 2
    I would recommend using a CSS preprocessor like SASS or LESS. This works ideally for such use-cases ;) – MMachinegun Mar 19 '15 at 20:24
  • While this doesn't directly solve your problem, you could achieve what you are talking about using a preprocessor like [LESS](http://lesscss.org/) by using a loop. Check out this answer http://stackoverflow.com/questions/21440789/loop-through-array-of-values-in-less. – Rorschach120 Mar 19 '15 at 20:25
  • I've heard of LESS, although I've never used it. I'll make sure to check it out. – polson136 Mar 21 '15 at 18:52

1 Answers1

1

You can somehow handle this using a gradient, with a very big size, and setting just the position

.container div {
  background-image: linear-gradient(yellow, blue);
  background-size: 20000px 20000px;
  }

.container div:nth-child(1) {
  background-position: 0% 0%;
}

.container div:nth-child(2) {
  background-position: 0% 30%;
}

.container div:nth-child(3) {
  background-position: 0% 100%;
}
<div class="container">
    <div>one</div>
    <div>two</div>
    <div>three</div>
</div>
vals
  • 61,425
  • 11
  • 89
  • 138