user3787706
user3787706

Reputation: 659

dynamic amount of divs = dynamic color change steps?

I want to have a dynamic amount of divs (sometimes 3, sometimes 10 etc), which should be colored based on a color gradient (say green to red).

So, when there are only two divs, make the first one #0F0, the second one #F00. But when there are 10 divs, make the first and last the same, but all those between change gradually from green to red.

Is there a way to do this with pure css? If not, how would you do it with javascript? I'm thinking about doing it with javascript right now, but it's gonna get reaaally complicated the way i think about it. any advice? thanks

Upvotes: 3

Views: 474

Answers (3)

Joseph Marikle
Joseph Marikle

Reputation: 78550

Here's a quick little script for just the two colors using hex values.

var elements = document.querySelectorAll('div');
var total = elements.length;
var step = 255 / (total - 1);

Array.prototype.forEach.call(elements, function(elem, i){
    var colorHexValue1 = (step * i).toString(16);
    var colorHexValue2 = (255 - step * i).toString(16);
    var formattedColor1 = ("0" + colorHexValue1).split('.')[0].slice(-2);
    var formattedColor2 = ("0" + colorHexValue2).split('.')[0].slice(-2);
    
    elem.style.backgroundColor = '#'+formattedColor1+formattedColor2+'00';
});
<div>content</div>
<div>content</div>
<div>content</div>
<div>content</div>
<div>content</div>
<div>content</div>
<div>content</div>

Upvotes: 1

leuquim
leuquim

Reputation: 655

CSS doesn't provide the functionality required to calculate values from an input like javascript does, so my personal advice would be to define container classes for different amounts of children. For example:

.two{
    div:nth-child(1){background-color: ...}
    div:nth-child(2){background-color: ...}
}

.three{
    div:nth-child(1){background-color: ...}
    div:nth-child(2){background-color: ...}
    div:nth-child(3){background-color: ...}
}

.four{
    div:nth-child(1){background-color: ...}
    div:nth-child(2){background-color: ...}
    div:nth-child(3){background-color: ...}
    div:nth-child(4){background-color: ...}
}

The limitations for this being it's not dynamic, but it can simulate the desired functionality up to as many classes you declare.

Upvotes: 1

Hugo
Hugo

Reputation: 71

Here a fiddle that does what you want ;)

https://jsfiddle.net/tkzr99vx/

It does create div with the amount you pass in the createDivs method.

Use rgb values as I did for simpler code. You still can use HEX values but you will have to convert it to rgb.

Upvotes: 1

Related Questions