Traditionally CSS (Cascading Style Sheets) are static files with .css extension linked to your web pages by using “link” meta tags inside header section of the page.


<link rel="stylesheet" href="my.css" type="text/css"/>


However, in many cases (especially for enterprise level applications) it makes sense to dynamically generate CSS code instead of producing huge amount of static files.

Just few benefits of dynamic or programmatic CSS (DCSS):

- CSS constants and conditional logic
- On demand user based calculations
- Encapsulated logic for styles
- Easy to maintain and support
- CSS size (don’t need to load stuff you don’t need)
- UI flexibility (easy to style pages for multiple scenarios)
- Scalability
- And many more …

CSS lives on the page and applied to the elements during rendering time on the client by the browser. Thus there are two options: server side and client side. You can write CSS generation logic by yourself of use one of hundreds available libraries.

Depending on the technology of your choice such as PHP, ASP.NET, Java or others you can use server side code to generate CSS along with your dynamic page or part of the page in case of AJAX request. Simple ASP.NET example would be using generic handler to serve CSS resources (note href value):


<link rel="stylesheet" href="mydynamicCss.ashx?cssCode=mainPage" type="text/css"/>


In this case, server side handler would generate css and serve it back to the client. Note: page rendering will be blocked.

Another option is to use client side JavaScript to generate CSS classes for example on page load (see CSSJS library).

Both approaches have benefits and drawbacks thus should be used according to particular application requirements.

Dynamic CSS for PHP: http://www.coolphptools.com/dynamic_css
Dynamic CSS Styling in ASP.NET: http://www.codeproject.com/KB/aspnet/ASPNET_Dynamic_Styling.aspx
CSSJS: http://revnode.com/oss/css/
JQuery: http://jquery.com







Answers and Comments