Question

I have a div, and in the div are many H3 elements.

For each H3 element (there are an arbitrary amount) the background-color is to be X shades lighter than the H3 before it.

I'm stuck on two things.

1: How I'd do this with CSS alone (could probably work out a hacky way to get this done in jQuery). 2: How I'd increase/decrease the colour (for the sake of simplicity assume the first H3 will be black and all of the rest lighter shades of grey).

Was it helpful?

Solution

Unfortunately, there's no way to do such a thing in CSS (you might be able to do something with nth-of-type), but that would only work if the only <h3> elements on the page are in the same parent element, and if you know ahead of time how many there will be, or at least how many max)

But it's actually pretty easy in JavaScript:

var h3s = document.getElementsByTagName('h3'), l = h3s.length, den = Math.max(l-1,1),
    darkest = [0,0,0], lightest = [255,255,255], // R,G,B - adjust as needed
    step = [
        (lightest[0]-darkest[0])/den,
        (lightest[1]-darkest[1])/den,
        (lightest[2]-darkest[2])/den
    ], i;
for( i=0; i<l; i++) {
    h3s[i].style.color = "rgb("
        +Math.round(darkest[0]+step[0]*i)+","
        +Math.round(darkest[1]+step[1]*i)+","
        +Math.round(darkest[2]+step[2]*i)
    +")";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top