October 11, 2010

want to change color at multiple places in one go !

Question by Rahul Utb

My problem is I have couple of divs in my page. All have header of similar color. Now if I have to change the color(for example background color) of all divs, I have to make changes as many divs I have. Is it not possible to just change or say write the color code at one place (like in a variable) and the then use that variable as color value in the embedded styles to all those divs. Something like javascript entities.

Answer by Yi Jiang

If you need variables in CSS, you might want to look at CSS pre-compilers (is this the correct term?), such as Sass, which does this Server-side and eases the pains for having many different color repeated across multiple rulesets.

Otherwise, when developing, try splitting your CSS files into individual components, such as typography.css, color.css etc. to help better organise them. You’ll still want to combine them after development is complete for better performance, but doing this does help keep things neater and tidier.

Lastly, you can always define large rules like this:

#header, #footer, #nav, #sidebar {
    color: orange; /* I like orange! */
}

Which would reduce redundancy somewhat. Using Javascript for styling and presentation should only be kept as a last resort; there are always tools available to keep your CSS tidy; you only need to use them.

Answer by Starx

Jquery solution

define all the divs with a specific class like

<div class="changeable"></div>

Then use jquery to change the background

$(".change").click(function() {
    $(".changeable").css("background","#000");
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!