17

As server-side generated HTML is trivial (and it was the only way to make dynamic webpages before AJAX), server-side generated CSS is not. Actually, I've never seen it. There are CSS compilers, but they generate CSS files which can be used as static.

Technically, it requires no special libraries, the HTML style tag should reference to the PHP(/ASP/whatever) templater script instead of the static CSS file, and the script should send out CSS content-type header - that's all.

Does it have cache problems? I don't think so. The script should send out no-cache etc. headers. Is it problem for designers? No, they should edit the CSS template (as they edit the HTML template).

Why we don't use dynamic CSS generators? Or if there's any, please let me know.

1
  • 3
    Less, Sass, SCSS, etc. Nov 6, 2011 at 0:12

8 Answers 8

14

The big reason why css is seldom generated dynamically (this is also true for javascript) is because they are good candidates for caching. CSS is a very flexible way to style your pages, with the right combination of classes, you can get all of the different parts of all of your different pages styled according to all sorts of cues all Without having to condition any of it in the CSS itself on what actually happens to be present on this pageview.

Simply because CSS doesn't need to be different per page leads to a very common practice of optimizing the cost of downloading it. Most sites cram all of the css for their whole site into a single download, so that parts that would apply to different page-views are present in only one downloaded file. With caching, your clients don't have to wait for it to download a second time. Maybe more importantly, you, as a content provider, don't have to pay the cost of uploading the content more than once; and you can even put the static css on a server that is better suited serving static content, which frees resources for actual dynamic content on your application servers.

This practice is so common, that many browsers just assume that the css is static; and are very reluctant to download CSS they already have; even if the users reloads the page. This special treatment applies only to CSS; other content types get reloaded as expected.

8

I believe your assumption is wrong: in my last project, the application was using server-generated CSS loaded by ajax (because, depending on the location of the map you were looking at, the page was branded with completely different styles).

However, usage cases where retrieving extra CSS by ajax would solve the problem are quite rare, this may be why you never encountered this: it's usually easier to maintain a set of stylesheets that are preprocessed at deployment time (LESS + minification) and cacheable (e.g. the next page will be able to re-use the stylesheet it cached before, so the initial time is shorter).

1
  • your point is useful but i think that is various case by case, so good_computer description is short and useful globally.
    – QMaster
    Aug 8, 2014 at 15:10
8

Actually, there are use cases for dynamic CSS. I've worked with three different kinds:

  1. Less — Less CSS is basically a CSS language extension that adds "dynamic behavior such as variables, mixins, operations and functions." It also allows "nested rules", which is very convenient. I have used Less mainly to make CSS writing less verbose by eliminating some of the repetition.

  2. URL rewriting — Just as a proof to your statement that there are no cache problems, I've used PHP to serve scripts as CSS files with the correct cache headers for a long time. I mainly do it to serve CSS files from libraries that are not inside the web root.

  3. Dynamic reports — On one project I worked on, we had a report builder for all kinds of data in the system. We output (inside style tags, as you mention) dynamic style rules mainly for colors that had been selected by the user in the report builder.

Note: When outputting CSS directly to a URL (like in 1 or 2) and not embedding it within a page that is already being generated by a script, you will add quite a significant load to the server over serving static content. So, if you have sizable traffic, even though you can do it dynamically every time, you'd want to cache it as a static file if your use case allows.


But why is it not more common? I think there is one main reason — CSS isn't really built to output content. So there simply isn't a great need. Beyond outputting dynamic colors chosen by the user, as we did, or possibly background-images (though if the image is content, then it is probably a good argument to use the img tag), what else do you need to do dynamically?

Most dynamic style changes can be produced by referring to different static CSS documents.

So it is certainly possible, as you thought, but there just aren't too many reasons to do it.

4

There's TWO separate aspects to loading CSS dynamically...

  1. Generating the CSS file dynamically on the server

    This is fairly straightforward, and a lot of websites do it. This is useful if you change your CSS based on some condition. For example, if you choose your site's theme based on the Geo location of the user.

  2. Loading a CSS file on demand via a JS script loader

    This could come in handy if you create a big part of DOM dynamically and then load the required styles. BUT As author of LABjs says...

    actually determining if a dynamically loaded CSS file has finished loading is actually quite complicated and challenging to do cross-browser. The "load" events don't fire as one would hope/expect. so adding such support would add a non-trivial size to LABjs

4
  1. We do this. All the time. Especially for things like customer-specific branding in a SaaS application, where colors etc. come from the database.
  2. It's a lot faster (from the user's viewpoint) to pre-generate the CSS before or during deployment, or during application boot if the application has a boot phase. We generally prefer to pre-generate static CSS files whenever possible.
  3. For maximum speed (from the user's viewpoint), it's best to deliver static CSS files to a CDN and to have the browser get them from the CDN, rather than from your application servers. This is generally possible only when the CSS files can be pre-generated before or during deployment, and where part of the deployment is delivering the pre-generated static CSS files to the CDN. CDNs are now very cheap and easy to use - check out Amazon's CloudFront and Rackspace's Cloud Files.
1

Does it have cache problems? I don't think so. The script should send out no-cache etc

All very well, but that's a significant piece of generally-static information that you're asking the user to download every time they load a page. So you'd better have a good reason for it.

Now what could that reason possibly be?

If you want to change a style based on various parameters then you do that by having multiple stylesheets and generating the HTML to download the correct one.

3
  • Generating different stylesheets based on parameters can become unmanageable if you have, for instance, a combination of three colors, each one selected from a palette of 256. You don't want to keep 16 million stylesheets around to cover all these, do you?
    – tdammers
    Nov 5, 2011 at 13:43
  • @tdammers: What's the use-case for that? Sounds like it would be better achieved using javascript.
    – pdr
    Nov 5, 2011 at 14:07
  • some kind of system where users can customize the appearance? You can't just give them a CSS editor, because that would expose a bunch of security vulnerabilities, but being able to pick a font and a few colors to personalize the user experience isn't exactly an exotic requirement, and if you do that, 256 colors is actually atypically low - try color pickers over the full 24-bit range instead. Javascript won't solve this as nicely as dynamic CSS would.
    – tdammers
    Nov 5, 2011 at 15:00
1

Dynamic CSS is fairly trivial, and even though its applications are more limited (seeing how dynamically-generated HTML with a static stylesheet solves most day-to-day needs, and CSS itself incorporates a few mechanisms to achieve semi-dynamic), I've seen it used on many occasions, and I use them myself whenever I need to.

Often, the 'dynamic' part does little more than combining several stylesheets into one (to reduce the number of HTTP requests) and minifying them (to reduce bandwidth usage), but simple things like variable substitution (e.g., using variables for colors used throughout the style sheet) can make your life much easier. However, since CSS has a fairly straightforward syntax with few caveats, a general-purpose text processing system or scripting language like PHP is usually enough for this, which is why you don't see many off-the-shelf CSS processing systems.

Maybe you have seen them in the wild, without recognizing them. Servers that send dynamic scripts usually use URL rewriting so that the URL becomes indistinguishable from statically-served content. This is necessary because some browsers (most notably IE) rely on extensions for correct MIME type detection under certain circumstances, ignoring (or discarding) any Content-Type headers you may have sent.

Regarding caching: Stylesheets are pulled in with GET requests, and making them cacheable is absolutely important for a decent user experience. You don't want to watch the page reflow as it re-downloads the stylesheet on every request. Instead, you should put all parameters that alter the output of your stylesheet processing into the query string; a different query string yields a different URL, which in turn causes a cache miss, so whenever the parameters are altered, the stylesheet will be re-downloaded, even if the client caches everything. If you really need CSS that is potentially different for each request and depends on side effects, consider putting the non-dynamic part into a statically-served stylesheet, and only serve those things dynamically that are absolutely required to be dynamic.

1

There are some scenarios were I'd love to use dynamic CSS, but more often than not I'm stuck with using designers who need a bit of help understanding CSS basics. Throwing a dynamic language in the mix might actually make a head explode.

Another way to look at this would be "some other guy is doing all the painful manual work, not really my problem, moving on . . ."

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.