Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing color incrementally

Tags:

css

#mainbody :nth-child(1){
    border-color: #FFCC00;
}
#mainbody :nth-child(2) {
    border-color: #FFAA00;
}
#mainbody :nth-child(3) {
    border-color: #FF8800;
}
#mainbody :nth-child(4) {
    border-color: #FF6600;
}

This is awkward, especially if you add another 20 children. Would it be possible to use something like this, feeding calc() the position and using it in rgb()?

Is there another way of doing this? (counter()?)

#mainbody h2 {
    border-color: rgb(255, calc( 255 / ( childposition / 4 ) ) ,0);
}

The following shows promise but I don't think rgb() accepts an internal counter():

body {
    counter-reset: headcolors 255;
}
h2:after {
    counter-increment: headcolors -34;
    content: "rgb(255," counter(headcolors) ",0);";
}
h2 {
    counter-increment: headcolors -34;
    color: rgb(255,counter(headcolors),0);
}
like image 835
J V Avatar asked Nov 25 '11 15:11

J V


3 Answers

Since you haven't said that you want a CSS only solution, I would recommend you to use a SASS/LESS based solution.

http://sassmeister.com/gist/925757ff999824ec0270

$baseColor: #FFCC00;

@for $i from 1 to 5 {
  #mainbody :nth-child(#{$i}) {
      border-color: adjust-color($baseColor, $green: ($i - 1) * 1);
  }
  $i: $i + 1;
}

The above code generates this:

#mainbody :nth-child(1) {
  border-color: #ffcc00;
}

#mainbody :nth-child(2) {
  border-color: #ffcd00;
}

#mainbody :nth-child(3) {
  border-color: #ffce00;
}

#mainbody :nth-child(4) {
  border-color: #ffcf00;
}
like image 127
Aniket Avatar answered Oct 13 '22 23:10

Aniket


Either use JS or one of the options suggested by pradeek. As of now, there is no way to use variables in CSS native language, if not by using counter-reset and counter-increment, but then you have to use them along with content, and that will change the content displayed inside the element, they will not treated as variables to use for operations.

Read here or here to understand why variables don't fit with CSS.

like image 27
Jose Faeti Avatar answered Oct 13 '22 22:10

Jose Faeti


With jQuery you can do the following when the page is loaded:

$(document).ready(function(){
    var startfrom = 204; // CC in Hex, the starting value for the green color
    var endto = 255 - startfrom; // the ending value for the green color
    var limit = 4;
    for(var i = 1; i <= limit; i++)
    {
        $("#mainbody :nth-child("+i+")").css("border-color", "rgb(255,"+Math.round(startfrom - (startfrom - endto)*(i-1)/(limit-1))+",0)");
    }
});

See the jsfiddle with 4 children and with 20 children

like image 2
clami219 Avatar answered Oct 13 '22 23:10

clami219