Journal
Time Sensitive CSS
9 February 2006 › 38 comments
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.
Discussion + Dissension
Comments closed after 2 weeks.



#1 Dennis Bullock
Excellent overview Nathan. This is something that will really be cool in several designs I have in my head.
#2 Matt Donovan
cool. very cool.
#3 Mike Stickel
I know I already mentioned this to you privately but I thought it might helpful if I posted a comment as well.
Since the variables ($server_month and $server_minute) are being set in the same line as they are being called — and they’re only being called once — you can shorten those PHP lines as follows (remove the extra spaces though, textile actually runs the code if I don’t include them):
@import "css/< ? php echo(date(m)); ? >.css";and:
background: url(img/minute/< ? php echo(date(i)); ? >.jpg) no-repeat 0 14px;#4 Veracon
Strong recommendation: REMEMBER to enclose strings in quotes; date(m) is wrong, date(‘m’) is right. If the server is set up the way I prefer, date(m) will raise a notice, since it tries to look for the constant ‘m’.
#5 Matt Heerema
Looks very sweet Nathan. Like I told you, almost widget-ish :)
#6 Rob
Great write-up bro. Now i just have to figure out how i can implement it…. MU AHAHAHAHA…
#7 Nathan Smith
Mike: I tried using that short-hand method, but the pages kept throwing an error. I’m not saying you’re wrong, just that my limited PHP skills seem to be getting in the way.
Veracon: Thanks for that reminder, I forgot to include the proper quotations. I’ve updated the example pages and the zip files with those changes.
I’m glad the rest of you guys have found it helpful, or at least entertaining. Rob, I’m not sure what to make of that evil laugh, dude. Sounds foreboding!
#8 Mike Montgomery
Hmm. In the clock demo page, it says:
“The files that drive this demo are very small, weighing only about 1MB total.”
Is this a typo, or is it a megabyte because you needed more than 12 + 60 images?
#9 Nathan Smith
Mike: The sum total of all the possible files is around 1MB. The initial page load is only about 50kb, and that’s just because I’m using high quality JPG’s.
#10 Elliot Swan
Very cool idea. I suppose following with this one could have some different styles to match the time of day as well..Something different for morning, afternoon, and night. Though I suppose that would better be done with JavaScript to account for different timezones.
#11 david b
Great start Nathan. and i only say start because i think as you said, your “just that my limited PHP skills seem to be getting in the way.”
not that mine are any greater. but I dont think it’s a very usable option as is, for two reasons. ( i am working this up right now and will come back and add a link to what i am working on in a bit.)
1. the use of 60+ images for the numbers, wow you had a lot of time on your hands huh ;) let php do the work there. seems you used verdana or something similar, if thats the case then just use the text display of the browser rather than feeding in all those images, anyone trying to restyle all that is going to have a cow :)
2. i know you said that this is not an excercise in ajax, but i think for the direction you are going with this, ajax if your best freind.
say for example i was reading an article with this implemented on it. and it took me say, 3 minutes to read the article for whatever reason. i would see the page flash 3 times. heaven forbid the page was image heavy , with a nocache involved the whole page would need to reload while i was tring to read. so yes i think that ajax could very well help you.
so like i said I am working on those things and will document them in a tut over on my site, when i have it up i’ll come back and post a link. I am still using your page just twisting it a bit ;)
ps i was only speaking of the time part, the month exercise is great.
#12 Nathan Smith
David: I was afraid this discussion might come up. Just to clarify, I didn’t make either example as something that should be used as-is, but just to show how PHP + CSS can be used based on time / date. Of course plain text would work best, but I needed to dynamically show how CSS could be updated.
What I find most exciting is how it can entirely change a whole site’s look and feel contextually to a certain season. For instance, a church design for Easter, etc. Elliot’s example is more what I had in mind for various practical uses.
#13 david b
you know after about an hour of working on it on my side i came back and reread the article and realized why you are doing what you are doing, so just ignore me:)
there isnt a better way to dynamically pull up the time using just css and php. i even tried to pull up the sleep function and try to recurse it using php, trying not to use javascript at all, since that was the basis of what you wrote and nothing, it still did the same as if i had used the refresh… if come across something or figure it out, I’ll let you know. but until then your tutorial stands.
#14 hendra
Man you really have a way with this coding and you do have taste…cool one Nate
#15 Nathan Smith
David: No problemo. I fully agree, that if one wants to have an actually usable clock, JavaScript / Ajax is the best way to go. I simply wanted to show how to modify and present differing “time release” CSS using only server-side code.
Hendra: Thanks, I appreciate it! Great quote of the day from MJ, by the way!
#16 Wesley Walser
Nathan, your last comment was exactly what I thought of when reading this. I don’t know why I hadn’t thought of just building those seasonal looks right into the site from the original design.
The implementation as you preface in the article is extremely elementary, but still good concept for changing only certain times of the year.
#17 Nathan Smith
Wesley: Yeah, it’s one of those things that’s so basic, that I couldn’t help but think, “Why didn’t this dawn on me sooner?” It’s also possible to do If / Else conditionals to offer specialized designs only part of the year, and a default the rest of the time. The potential for this method is pretty open-ended.
#18 david b
ahhh MJ is cool, a ‘real human’. doesn’t let, or rather learned not to through maturity, his head become so huge with fame that he does not identify his own shortcomings.
yeah the monthly css change is great. i bet when you see yahoo and google and all the big searchengines change over the holiday’s like they always do, they are using some overly complex way of changing their css, would be funny if one or more of them came ( meaning one of there webmaster ) here and saw how simple this was and started usingit ;), might just drop my friend at yahoo an email… yeap, might just do that.
mind you he is just a tech guy but he knows the design team.
#19 Dustin Diaz
Cool. You can probably do some fun stuff with gmdate to serve the appropriate style sheet for the time of day depending on what part of the world you’re in. That would indeed be fun.
#20 Memetics
Thank you for the tip.
Here is a short function I sometimes use for randomly changing css.
mt_rand(Int Min, Int Max);
eg:
@import “css/< ? php mt_rand("1", "30"); ? >.css”;
and:
background: url(img/random/< ? php mt_rand("1", "50"); ? >.jpg) no-repeat 0 14px;
#21 Nathan Smith
Dustin: Yeah, that would be pretty sweet. You could also localize the page presentation to the business location, in cases where the server is in a different geographical area than the respective site. I could see it being useful on contact pages, to indicate that current business hours are / not in effect.
Memetrics: Thanks for that bit of code. That would be pretty funky, to have all the site’s backgrounds randomized. In that case though, I don’t think I’d want to be the person responsible creating the multiple design possibilities! ;)
#22 Lars Toomre
This is a really cool piece of CSS coding. Thanks so much for the write-up. I plan on using htis shortly on my small business site.
#23 Nathan Smith
Lars: You’re welcome. Shoot me an email when you are done implimenting the changes. I am curious to see how people put this crazy method to use.
#24 Dave
Nice, unbelievable that nobody (as far as I know) really worked this out before. Great work, people will be quick to figure out some sexy possibilities for this, (maybe combined with AJAX?).
#25 Yannick
That is pretty good Nathan! Nicely done.
#26 Jauhari
Thanks, this really help article
#27 Nick Presta
I used a similar method to server different header images in a previous design. Very useful indeed.
#28 P.J. Onori
I apologize beforehand if this has been brought up in the comments…
I think you could go a step further with this idea and think of it as Data-sensative CSS. This is a subject I’m very interested in, as I haven’t seen much of it on the web yet. While time is a perfect example of this idea, really many different kinds of data (weather, traffic stats, number of comments, etc.) could be interesting exercises in this method.
#29 Nelson Ip
How do I correct the time shift ??
My city is Hong Kong, So need +8Hrs
#30 Nathan Smith
P.J. – I agree, this could more aptly be named “Data Sensitive” CSS, because with PHP you could even have the styles served be based on web services such as weather, as you’d mentioned. Traffic stats would be cool too.
Nelson: To correct for a time shift, you might want to check out the official PHP manual for the topics of – Date and Time. I hope that helps you out.
#31 Tommy
I’d love to use this in another way – to set the visibility of div’s based upon a date range.
Obviously this could be done by changing the visibility: property within a css sheet that would be called based upon what the date was and having a corresponding css sheet. Probably just need to add a simple if / then statement.
Any clue as to how I could modify the php to accomplish this??
#32 Nathan Smith
Tommy: Just give a number to each
divyou’d like to hide, corrosponding to the time of day you want it to be hidden. For instance, if you have adivyou want to be hidden at 2:00pm, you would give it anid="14", because it’s the 14th hour of a 24 hour day. Then, in your CSS set that todisplay: none.#33 ’Mas
Tommy –
Let’s say you want to only display a div during your regular business hours (8-5). You could create a “hide” class in your stylesheet and then use the following insert just before the closing ”>” of the div tag: < ?php if (date('G') < 8 || date('G') > 17) echo ” class=\”hide\””; ? >
This will add the “hide” class to the div when it’s after hours.
#34 Steven Hambleton
In the hope that I don’t sound dumb but here goes –
Can you call PHP from a .css file or does the PHP have to be in the CSS in the head of the document only?
#35 Chad Lawson
Nathan,
Thanks so much for the PHP/CSS idea of time/date/data-sensative CSS. I like the thought of letting PHP change to various “seasonal” elements.
Regarding the clock, however, I would like to address one issue. Viewing the source, it appears that the time doesn’t actually appear in the XHTML. While this and the CSS may be perfectly valid, it does nothing for accessibility. I may be wrong as this was a cursory glance.
Could you just simply use FIR (image replacement) or have the time there in XHTML (a div/span or something) and hide the “accessible-version” with CSS?
Just my $0.02. Thanks again for the great ideas.
Chad
#36 Nathan Smith
Chad: Looking back on it, I realize I should’ve made my clock example more accessible. The reason it was sort of slapped together haphazardly is that I didn’t intend people to actual put it to use as-is. In fact, for a clock JavaScript is probably the best way to go. I just wanted to show an obviously dynamic way of changing aspects of CSS, and figured waiting a whole month to watch an example change wouldn’t be too exciting. :)
#37 Nick Presta
A little late of me to post, but instead of using 85 images, you could use PHP to split the hour/minute/seconds in half (to give two numbers each) and only use number images 1-9 and just reuse them.
http://nickpresta.ath.cx/scripts/sonSpringClock/
Check it out. I had to create a function to split the hour/minute/etc (uses str_split within it) but it only uses 12 images (0-9, am, pm) although uses 3 more divisions (to hold each number).
I also switched to absolute positioning.
#38 Nathan Smith
Hey Nick, that’s pretty cool. Although, if we really wanted to be efficient, it’d probably be best to just use actual text. Then again, it wouldn’t illustrate the method of using PHP with CSS. Here’s another example: Weekly Calendar.