Time Sensitive CSS

— Topic: CSS

Recently, there’s been some discussion on the Godbit forum about how to serve dynamic, time sensitive CSS with PHP. I got to thinking, and the steps necessary to make this work are actually pretty easy. First off, let me say that most hardcore programmers will probably scoff at the simplicity of these examples. However, a hardcore programmer I am not, so basic tutorials are what I enjoy. Also, please know that this is not an exercise in JavaScript / Ajax. It is simply a way to provide unique CSS based on date and time.

Month Based CSS

Demo: View Month Example | Download Month.zip

To start, I wanted to show how inclusion of various CSS files could be used to change aspects of a site design. I made a very rudimentary example that queries the server to get the date, and returns a CSS file via import based on the current month. There is one basic stylesheet, and twelve possible imported files. The actual example is nothing fancy, just a proof of concept.

@import 'css/<?php echo date('m'); ?>.css';

/* Returns This: */

@import 'css/02.css';

I have replaced the name of the imported CSS file with a short snippet of PHP, which in turn generates a numerical value (1-12), and appends the *.css file extension. The implication is CSS that self-updates throughout the year.

PHP + CSS Clock

Demo: View Clock Example | Download Clock.zip

This clock demo is actually pretty cool. I tried to make it look sort of slick, in the vein of Apple dashboard widgets. Instead of having external CSS files, I have just kept it within the head of the document to make it easier to view the source. Instead of calling a different style import, I am just dynamically replacing the background images every 60 seconds with PHP and an old-school meta refresh. No JavaScript was harmed in making this demo.

background: url(img/minute/<?php echo date('i'); ?>.jpg) no-repeat 0 14px;

/* Returns This: */

background: url(img/minute/30.jpg) no-repeat 0 14px;

The code listed above is all that it really takes. The server is asked for the current time and then returns a numerical value between 1-24 for the hour and 00-59 for the minute. This yields a total of 85 images used, with one for the clock itself. The corrosponding ID is then updated with a new background. I hope these examples have proven helpful to you. Feel free to reuse them.

JS Tutorial, JavaScript Tutorial, JavaScript Guide, Learn JavaScript JS, How To Learn JS, Learning JavaScript
Promote JavaScript


The thoughts and opinions expressed here are mine alone, and are not necessarily shared by any other living person.