I a working on a CMS and I want to be able to add CSS via the administrative control panel.
When I add css should I just append it to the bottom of the stylesheet I have or is it best to add the data to a DB and then get it using a handler.
The way I see it they both seem to have advantages.
writing to file:
It is simple and requires very little code
The file is portable and can be copied like any other css file
writing to a DB:
I have more control
I can load only the classes I need for each document
Having done both in previous lives, I think the answer depends on who is maintaining the CSS.
If it is a simple-interface for a non-technical user to manage a few simple styles, I would store this in the database, but as structured data, not raw CSS, and generate the CSS itself at run time. However as Sohnee mentions, you need to ensure it is not generated for every request, as this would be an unnecessary overhead – you should generate to a flat file, or cache effectively.
If it is an interface for a web-developer type person, who understands the concepts of files, and you want to give them full access to write any css they like (and you trust them!) then I would store it as a file (if I were the developer, I would want it to be using my raw CSS). However, I would not append it to the existing stylesheet (assuming that is the default base set of styles for the site) I would have a separate stylesheet for user-defined styles, called in the page with a separate link tag. This will keep the site ‘code’ separate from its ‘content’. Note also what Zhaph – Ben Duguid says here about ensuring the browser does not cache old versions by adding some sort of version parameter to the URL.
I’d say only loading the classes per document would generally be a bad idea. Browsers are tuned for CSS caching, so you nearly always will be better off calling all your CSS from external files, with the appropriate caching headers.