1

So let us say I have loads of stylesheets on a Django site. CSS and JS files are under static/ in either an app's directory or the global site directory (if it's a common file). I have different color themes going along with different pages, only changing some color values across stylesheets.

Instead of having one whole different stylesheet file for each color theme, and also saving me time should I want to change one single color in the theme that repeats multiple times across the file, I would like to use variables (and for all I know CSS3 variables are both yet unsupported and looked down upon by programmers and designers).

Obviously, being on the static directory, I can't send context variables to these files (they aren't called by a Python view request), so here lies the problem: how can I massively change repeated color values in CSS using Django?

3
  • Is the filesystem read-write or read-only? Commented Nov 26, 2013 at 17:06
  • (some systems, esp. google app engine, don't let you read /static, and don't let you write anywhere.) Commented Nov 26, 2013 at 17:09
  • It's being tested locally. I just want a solution for my problem - I can't send context variables to a file in /static, but I wanted to somehow have a reference variable so I can massively set and change CSS color values just like you would change a variable value in a script. Commented Nov 26, 2013 at 17:11

1 Answer 1

3

You can use the CSS property of cascading to your advantage! Don't store colours in your stylesheet, you can specify them in your <head> style. For example:

<head>
<link rel="stylesheet" type="text/css" href="xxx"/>
<style>
body
{
    background-color: {{ colour }};
}
</style>
</head>

The colour variable can be set as global in your views. Or better yet, define a class, list or a dictionary with various colours you want to use. Many options here. I think I'd go for

Colours={'Grey': ['#999', '#ccc', '#ddd'], 'Blue': ['#00f', '#77f', '#aaf']}

Now if you want a subpage to be blue you send Colours['Blue'] (as Colour in my example below) in you context and use one item for the background colour, one for text and one for miscellaneous:

<style>
body
{
    background-color: {{ Colour.0 }};
    color: {{ Colour.1 }};
}
div.misc
{
    background-color: {{ Colour.2 }};
}
</style>
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent solution. Makes the code slightly less portable, so if someone else runs into this answer, my suggestion is that you make a three-level template-extend: a base template, a template that extends the earlier (with the CSS), a third that adds different widgets if you need, and the final, page-level extension.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.