How to Create a Time Based CSS Style Sheet Switcher

How to Create a Time Based CSS Style Sheet Switcher

Tutorial Details
  • Program: PHP, CSS, jQuery UI
  • Difficulty: Beginner
  • Estimated Completion Time: 60-90 Minutes

Final Product What You'll Be Creating

Style switchers have become a popular feature on websites these days. CSS style sheets allow a Web Designer to change the look and feel of a website with little effort. Some sites use “Day” and “Night” type of style switchers that automatically change the site theme based on the time of day.

This tutorial shows you how to create a time based CSS style sheet switcher using PHP that lets you change multiple style sheets at once at specific times of the day. There’s also a little bit of jQuery UI thrown in just for fun!


Why PHP instead of JavaScript?

The one drawback to using PHP for a time based CSS style sheet switcher is that the time is based on either the web hosting server or on a “time zone” set in the script.

When I was building my personal portfolio site, I created a time based style sheet switcher using JavaScript and jQuery. The time function of the script worked correctly. However, there was always a brief “flash” of the default style sheet when the web pages loaded.

JavaScript heavy websites can have problems with conflicts between various JavaScript scripts. I decided to use PHP instead for the CSS style sheet switcher. Because PHP is server side, there were no JavaScript conflicts and the script worked as expected.

The one drawback to using PHP for a time based CSS style sheet switcher is that the time is based on either the web hosting server or on a “time zone” set in the script. With JavaScript you can set time functions to be based on a user’s computer.


Before We Begin

If you are new to PHP, you need to set up and configure a server environment on your local computer (PHP files can not be viewed in a web browser). My personal preference is XAMPP. This article includes a few software options and basic instructions on how to set up a local server.

Although you can use Notepad to create and edit PHP files, a code editor can be very helpful when writing web pages in PHP and other programming languages. Please refer to these articles for additional information on choosing a code editor:

The code used in the tutorial creates a basic CSS style sheet switcher and you can view the demo here. The source files include two additional demos.

Now, let’s get started!


Step 1: Create the 1st CSS Style Sheet (Night)

Create a CSS style sheet called style-1.cssand include the following code:


/*  Default Styles
--------------------------------------------------- */

body {
	margin: 0px;
	padding: 0px;
	background: url("../images/bokeh_2.jpg");  
	background-position: top left;
	background-repeat: no-repeat;
	background-attachment: fixed;
	background-color: #666;
	font-size: 20px; 
	font-family: Arial, Helvetica, sans-serif;
	color: #fff;
	text-align: left;
}

#wrapper	{
	width: 965px;
	margin: 0 auto;	
	position: relative;
}

a:link, a:visited, a:active {
	color: #99ccff;
}

a:hover {
	color: #0073ea;
}

.content_container_1	{
	float: left;
	width: 650px;
	margin: 0px 0px 60px 0px;
}

p.main_description	{
	margin: 5px 0px 50px 0px;
	text-align: center;
}
/* Main Image
--------------------------------------------------- */

.main_image	{
	background: url("../images/main_image_1.jpg");  
	background-repeat: no-repeat;
	width: 630px;
	height: 425px;
	border: #fff solid 10px;
	margin: 40px 0px 10px 0px;
}
/*  Tabs 
--------------------------------------------------- */

#tabs p	{
	font-family: Arial, Helvetica, sans-serif;
	font-size: 20px;
}

a.tabs_link_1:link, a.tabs_link_1:visited, a.tabs_link_1:active { 
	text-decoration: underline;
	color: #0073ea;
	font-weight: bold;
}

a.tabs_link_1:hover { 
	text-decoration: underline;
	color: #ff0084;
	font-weight: bold;
}

#tabs .tabs_img	{
	float: left;
	background-color: #ddd;
	padding: 8px;
	margin: 0px 12px 0px 0px;
}


Step 2: Create the 2nd CSS Style Sheet (Morning)

Open style-1.css and save it as style-2.css. Change the body background image from bokeh_2.jpg to bokeh_4.jpg. Change main_image_1.jpg to main_image_4.jpg.


Step 3: Create the 3rd CSS Style Sheet (Afternoon)

Use style-1.css or style-2.css to create a 3rd style sheet style-3.css. Change the body background image to bokeh_3.jpg and the main image to main_image_5.jpg


Step 4: Create the 4th CSS Style Sheet (Evening)

Create a 4th style sheet style-4.css. Change the body background image to bokeh_1.jpg and the main image to main_image_8.jpg

For steps 2 through 4, feel free to change other elements like font colors and image borders. Instead of using the images provided in the source files, you can use your own images to create custom CSS styles.


Step 5: Download jQuery and jQuery UI

To show how the PHP script changes multiple style sheets at once, jQuery Themeroller Themes are being used to style the tabbed content area of the web page.

Go to the jQuery UI Download Page and download the “Flick” and “Start” themes.

Next, go to the official jQuery website and download jQuery.


Step 6: The Markup

Create a PHP file that includes the following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<!-- CSS style sheets -->
<?php include("style sheets.php"); ?>
<!-- jQuery / JavaScript -->
<script type="text/javascript" src="js/jquery-1.6.3.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.16.custom.min.js">></script>
<script type="text/javascript">
	$(function() {
		$( "#tabs" ).tabs();
	});
</script>

<meta name="description" content="This demo uses PHP to change multiple CSS style sheets (Main CSS and jQuery UI Theme) at specific times during a 24 hour period. The timezone for this demo is set to Australia/Melbourne." />
<meta name="keywords" content="time,based,css,stylesheet,switcher,php" />
<title>Simple Time Based CSS Style Sheet Switcher</title>

</head>
<body>

<!-- Begin Wrapper -->
<div id="wrapper">

<!-- Begin Content Container 1 -->
<div class="content_container_1">

<!-- Main Image Switches at Set Times -->
<div class="main_image"></div>
<p class="main_description">
Main Image changes at the times set in PHP Script (Australia/Melbourne).
</p>

<!-- Begin Tabs Area -->
 <div id="tabs">
	<ul>
		<li><a href="#tabs-1">About Envato</a></li>
		<li><a href="#tabs-2">Marketplaces</a></li>
		<li><a href="#tabs-3">Tuts+ Network</a></li>
	</ul>
	
	<div id="tabs-1">
	<p>
	<img class="tabs_img" src="images/envato_1.jpg" width="300" height="195" alt="About Envato" />
	Envato is a startup based out of Australia with people around the world and sites serving pages every second. We started in a living room in 2006 and have been steadily working to build our company into a world-class contender. Our background is creative, we love open source, we believe that work is about way more than just making money, and we're totally committed to making products that are awesome!
	</p>
	<p>
	<a class="tabs_link_1" href="http://envato.com/" target="_blank" title="Visit The Envato Website">Visit The Envato Website</a>
	</p>
	</div>

	<div id="tabs-2">
	<p>
	<img class="tabs_img" src="images/marketplace_1.jpg" width="300" height="195" alt="Marketplaces" />
	The Envato Marketplaces allow anyone to buy or sell digital goods like WordPress themes, background music, After Effects project files, Flash templates and much more. The marketplaces are home to a thriving community of over 500,000 users, authors and buyers and every day hundreds of new files are added.	
	</p>
	<p>
	<a class="tabs_link_1" href="http://themeforest.net/" target="_blank" title="Visit the Theme Marketplace">Visit the Theme Marketplace</a>
	</p>
	</div>

	<div id="tabs-3">
	<p>
	<img class="tabs_img" src="images/psdtuts_1.jpg" width="300" height="195" alt="Tuts+ Network" />
	At Envato we're very passionate about education, that's why we've created one of the most popular networks of educational blogs around. Tuts+ serves up over 18 million pageviews a month across its many subsites on subjects like graphics, web development, audio production, iPhone development and motion graphics.
	</p>
	<p>
	<a class="tabs_link_1" href="http://tutsplus.com/" target="_blank" title="Visit Tuts+ Hub">Visit Tuts+ Hub</a>
	</p>
	</div>

</div> 
<!-- End Tabs Area -->

</div>
<!-- End Content Container 1 -->

</div>
<!-- End Wrapper -->

</body>
</html>

Step 7: PHP CSS Stylesheet Switcher Code

Create a PHP file that includes the following code:

<?php

date_default_timezone_set("Australia/Melbourne"); // Set default time zone

$time = date("H"); // Set the time in 24 hour format

if (00 <= $time && $time < 07) // 12:00am to 7:00am   Night
	{
	echo 
'<link href="css/style-1.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/flick/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
	}

elseif (07 <= $time && $time < 12) // 7:00am to 12:00pm   Morning
	{
	echo 
'<link href="css/style-2.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/start/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
	}

elseif (12 <= $time && $time < 18) // 12:00pm to 6:00pm   Afternoon
	{
	echo 
'<link href="css/style-3.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/start/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
	}

else // all other hours   Evening
	{
	echo
'<link href="css/style-4.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/flick/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
	}

?>

Breakdown of the Markup

PHP Include for rel="stylesheet" Links

The script for the CSS Style sheet Switcher is going to be contained in a PHP include file called stylesheets.php.

A PHP include() statement includes and evaluates a specified file. The stylesheets.php include file is referenced by this code:

<!-- CSS style sheets -->
<?php include("style sheets.php"); ?>

Because we are using a PHP script to change CSS style sheets at set times, the rel=”stylesheet” links will be generated by the PHP script.

Reference jQuery and jQuery UI Libraries

We need to make sure that the web page references the jQuery and jQuery UI libraries.

Between the head tags of the web page the following code has been added:

<!-- jQuery / JavaScript -->
<script type="text/javascript" src="js/jquery-1.6.3.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.16.custom.min.js"></script>

Initialize jQuery UI Tabs

This tutorial includes jQuery UI Tabs using the default functionality. The following code initializes the tabs:

<script type="text/javascript">
	$(function() {
		$( "#tabs" ).tabs();
	});
</script>

Container Div for jQuery UI Tabs

<!-- Begin Wrapper -->
<div id="wrapper">

<!-- Begin Content Container 1 -->
<div class="content_container_1">

(Ending </div> tags for Wrapper and Content Container 1 are shown in the Code block for the Markup of the jQuery UI Tabs)

Most of the jQuery UI Widgets are programmed to expand to 100% width of the content area where they are placed.

The container div content_container_1 has been set to a fixed width of 650px in the CSS so that the tabbed content area does not expand the entire width of the screen.

Main Image Markup

In order for the main image to also be changed at set times using the PHP script, it needed to be included on the web page as a CSS background image.

So instead of adding the image to the web page using markup like this:

<img src="main_image_1.jpg" width="630" height="425" alt="Image" />

It was added to the web page as a CSS background image of a <div> with the class “main_image”, like this:

<!-- Main Image Switches at Set Times -->
<div class="main_image"></div>
<p class="main_description">
Main Image changes at the times indicated.
</p>

Markup for the jQuery UI Tabs

The below markup adds the tabbed content area that is powered by jQuery UI and has been styled using jQuery Themeroller Themes.

<!-- Begin Tabs Area -->
 <div id="tabs">
	<ul>
		<li><a href="#tabs-1">About Envato</a></li>
		<li><a href="#tabs-2">Marketplaces</a></li>
		<li><a href="#tabs-3">Tuts+ Network</a></li>
	</ul>
	
	<div id="tabs-1">
	<p>
	<img class="tabs_img" src="images/envato_1.jpg" width="300" height="195" alt="About Envato" />
	Envato is a startup based out of Australia with people around the world and sites serving pages every second. We started in a living room in 2006 and have been steadily working to build our company into a world-class contender. Our background is creative, we love open source, we believe that work is about way more than just making money, and we're totally committed to making products that are awesome!
	</p>
	<p>
	<a class="tabs_link_1" href="http://envato.com/" target="_blank" title="Visit The Envato Website">Visit The Envato Website</a>
	</p>
	</div>

	<div id="tabs-2">
	<p>
	<img class="tabs_img" src="images/marketplace_1.jpg" width="300" height="195" alt="Marketplaces" />
	The Envato Marketplaces allow anyone to buy or sell digital goods like WordPress themes, background music, After Effects project files, Flash templates and much more. The marketplaces are home to a thriving community of over 500,000 users, authors and buyers and every day hundreds of new files are added.	
	</p>
	<p>
	<a class="tabs_link_1" href="http://themeforest.net/" target="_blank" title="Visit the Theme Marketplace">Visit the Theme Marketplace</a>
	</p>
	</div>

	<div id="tabs-3">
	<p>
	<img class="tabs_img" src="images/psdtuts_1.jpg" width="300" height="195" alt="Tuts+ Network" />
	At Envato we're very passionate about education, that's why we've created one of the most popular networks of educational blogs around. Tuts+ serves up over 18 million pageviews a month across its many subsites on subjects like graphics, web development, audio production, iPhone development and motion graphics.
	</p>
	<p>
	<a class="tabs_link_1" href="http://tutsplus.com/" target="_blank" title="Visit Tuts+ Hub">Visit Tuts+ Hub</a>
	</p>
	</div>

</div> 
<!-- End Tabs Area -->

</div>
<!-- End Content Container 1 -->

</div>
<!-- End Wrapper -->

The Menu “Tabs” are generated by an unordered list. The content sections are generated by <div> tags that have unique IDs that correspond to anchor links in the <li></li> tags.

For example: <div id=”tabs-1″> corresponds with <a href=”#tabs-1″>


Breakdown of PHP Stylesheet Switcher Code

Set the Default Time Zone:

date_default_timezone_set("Australia/Melbourne"); // Set default time zone

The code date_default_timezone_set sets the default timezone used by all date/time functions in a script.

If the script does not include date_default_timezone_set, then the web hosting server time will be used for all date/time functions in the script.

Please refer to the List of Supported Timezones to find the appropriate timezone for your location.

Newer versions of PHP incorporate “Daylight Savings Times” into the functionality of date_default_timezone_set. Some older versions of PHP do not take “Daylight Savings Times” into account.

Set the Time in 24 Hour Format:

$time = date("H"); // Set the hour in 24 hour format

date(“H”) formats the local time/date in a 24-hour format of an hour, with leading zeros. Click Here to view information about the 24-hour clock.


Breakdown of If, Elseif, Else Statement

I’ve broken down the rest of the PHP code to show how the PHP script will function line by line. There are several functions being utilized in the code including:

if

if (00 <= $time && $time < 07) // 12:00am to 7:00am   Night
	{
	echo 
'<link href="css/style-1.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/flick/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
	}

If 00 (midnight) is Less than or equal to current time AND current time is Less than 07 (7:00am) Then the script will apply style-1.css and flick CSS style sheets.

elseif

elseif (07 <= $time && $time < 12) // 7:00am to 12:00pm   Morning
	{
	echo 
'<link href="css/style-2.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/start/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
	}

If 07 (7:00am) is Less than or equal to current time AND current time is Less than 12 (12:00pm) Then the script will apply style-2.css and start CSS style sheets.

elseif

elseif (12 <= $time && $time < 18) // 12:00pm to 6:00pm   Afternoon
	{
	echo 
'<link href="css/style-3.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/start/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
	}

If 12 (12:00pm) is Less than or equal to current time AND current time is Less than 18 (6:00pm) Then the script will apply style-3.css and start CSS style sheets.

else

else // all other hours   Evening
	{
	echo
'<link href="css/style-4.css" rel="stylesheet" type="text/css" media="screen" /><link href="css/flick/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" media="screen" />';
	}

If NONE of the conditions are met in the “if…elseif” statements, Then the script will apply style-4.css and flick CSS style sheets.


Conclusion

With CSS, you can create many different styles for your web pages. Using PHP, you can apply those styles dynamically to your website. Throw in a little jQuery UI, and your web pages will not only be fun for you to create, but fun for your visitors as well!

If you have any questions about this tutorial, please ask them below, Thank you so much for reading!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://maomuffy.blogspot.com/ Mfawa Alfred Onen

    This is really beginner stuff but well appreciated!

  • Aaron

    Step 7 is showing
    $time &= date(“H”); // Set the time in 24 hour format

    But in the PHP breakdown it shows
    $time = date(“H”); // Set the time in 24 hour format

    ;)

    • http://www.ssiddharth.com Siddharth

      Was a tiny issue with the code highlighting plugin. Fixed now. Thanks!

  • http://www.keithbluhm.com Keith

    I suppose beginners can give tutorials as well!

    $time &= date(“H”); will most likely yield an Undefined variable: time error. I would drop the ampersand; it’s worthless.

    The times should ideally be compared as strings since date() returns a string, but that is just nit-picking… or even better cast the 24 hour format to an integer and compare integer values.

    I am also wondering how jQuery and jQuery UI made it into the tutorial. I realize it’s for the demo, but this could very easily been packed into a “Good Morning!”, “Good Afternoon!”, “Good Evening!” tutorial. Quite an overkill for such a simple piece of logic.

    Meh…

    • http://www.webcodepro.net/ Janet Wagner
      Author

      Hi Keith, please see Siddarth’s comment above. The “$time &= date(“H”);” was because of a tiny issue with the code highlighting plugin which is fixed now.

      This tutorial is actually aimed towards beginners new to PHP. I noticed that the difficulty says “Intermediate” but it really should be “Beginner” (sorry, small oversight on my part, reused tutorial template that says Intermediate).

      And you are right, the reason jQuery and jQuery UI made it into the tutorial was because of the demo. Also, because I really like jQuery and jQuery UI! Hopefully this tutorial will benefit PHP beginners as intended.

      Thank you for your comments and your suggestions, they are really appreciated!

      • http://www.keithbluhm.com Keith

        Hey Janet, no worries… but my ampersand reference (no pun intended) was up prior to the author’s explanation and fix.

        I do realize that without all the jQuery magic, this is a very [very] basic tutorial that [assumedly] would have never made cut. jQuery is added content and thus added relevance. ;)

  • Oscar B.

    So cool. :)

  • http://kontrary.com Rebecca

    This is so cool – I’ve always wondered how to do this, but of course, it seems obvious now. Thanks for the great tutorial!

  • http://www.umbraprojekt.pl mingos

    It should be
    if (’00′ <= $time && $time < '07')
    Otherwise, you’re actually using octal numbers instead of strings. You got away with this one since 07 equals 7 in decimal and happens to be a valid octal number. 08 is not a valid octal number and had you used it, your program would end up misbehaving.

    • http://www.umbraprojekt.pl mingos

      Also, the time interval mentioned above is not 0:00-7:00, as your comment implies, but rather 00:00:00 to 06:59:59 ;)

      • http://fractalfragger.com Fractal

        JEEZ man lay up the guy has produced a good tutorial for the beginners out there just remember you were once a beginner would you like it if you got stick like this???

        Janet – GOOD TUTORIAL :-) Keep it going!!!

      • http://www.webcodepro.net/ Janet Wagner
        Author

        Hi Fractal – Thank you, I really appreciate it !!! Janet

      • http://www.umbraprojekt.pl mingos

        @Fractal, I never questioned the quality or usefulness of the tutorial. But I have faced too many “<" vs "<=" issues to know how frustrating debugging those can be. Especially for beginners. I'm not nitpicking out of malice, but rather to let the beginners out there know what they should look out for.

    • http://www.keithbluhm.com Keith

      I caught the octal numbers as well, but left it out of my comments to avoid being *too* overbearing. :)

    • http://www.webcodepro.net/ Janet Wagner
      Author

      Hi Mingos, You are right, without the single quotes the PHP code is not a string. This is a good example of why it is important to triple check your code, I should have caught that. Thank you for pointing out my error! :)

      • http://www.umbraprojekt.pl mingos

        No problem, Janet. I just thought it was an important thing to remark since my first thought was to use three stylesheets instead of four (the first time interval would be 0-8). I do notice such problems right away because I work full time as a PHP programmer, but if someone’s only beginning to work with the language, it might be frustrating to see the script’s misbehaviour without any error output (PHP will, sadly, convert ’08′ to a zero without complaining about the wrong number format…).

  • http://www.federicobucchi.com Federico Bucchi

    Him shoud use 7 and not 07?

  • http://blog.lievheid.nl Jan-Marten de Boer

    For the time based stylesheet, I would’ve gone for something like:
    $sheet = ceil( date(‘H’) / 6 ); // 1, 2, 3 or 4

    And then echo that into a link tag. If you explain that properly, you not only learn them a bunch, but also stay within the right audience.

  • cahva

    As mingos pointed out, author should really fix that octal issue. I propose that you cast it to integer:

    $time = (int) date(“H”);

    ..and later on use it without leading zeros in the if/else.

    Also I didnt like repetition in the code. Why echo everything in every if/else? The only changing thing is the stylesheetname so its better to just set a variable and use that:

    if (0 <= $time && $time <7) // 12:00am to 7:00am Night
    {
    $style = ‘style-1.css’;
    }

    elseif (7 <= $time && $time < 12) // 7:00am to 12:00pm Morning
    {
    $style = ‘style-2.css’;
    }

    and in the end print the html code including that $style.

    • http://www.umbraprojekt.pl mingos

      cahva, this wouldn’t work either, as casting an erroneous octal number to integer will still be an issue with ’08′ and ’09′. The best approach would be to use the single digit number format:
      $time = date(‘G’);
      This will produce ’7′, ’8′, ’9′… instead of ’07′, ’08′, ’09′, allowing you to compare the strings to regular integers: if ($time == 8) { … }

      • cahva

        Well it will work because date function returns string “08″, not octal and when you cast it as int, it will cut the leading zero from it. But ofcourse using date(“G”) is much more better solution :) Should’nt post anything after 3a.m ;-)

    • JackinaBox

      I’d have to say that this is a bad example, esp if you trying to teach people to use PHP. Code is bloated with to much repetition and everyone knows “the faster the code runs, the faster the webpage loads”. Even if this script once amended only removes milliseconds from the whole equation (If this is your coding practice it would be more like seconds).

      Don’t teach the wrong methods know, only for the learner to learn its wrong later on down the line.

      (I’m suprised this also made it through the envato review tbh).

      Just my opinion and thats all :)

  • http://wpthemepower.com Zeeshan

    Pretty nice concept :)

  • http://www.stormbloom.com Jose

    This is great. Now I can’t wait till someone make something like this that gradually transitions form day to night over a 24 hr period.

    • http://www.umbraprojekt.pl mingos

      Jose, with some CSS magic and a dynamic style sheet (or at least a few dynamically generated properties), it is actually very easy to create a seamless transition :).

  • http://www.paulund.co.uk Paul

    Good tutorial really like the idea of a different stylesheet for different times of the day. Nice work.

  • http://www.deluxive.se Christopher Anderton

    <SCRIPT LANGUAGE=”JavaScript”>
    <!– Begin
    function getCSS()
    {
    datetoday = new Date();
    timenow=datetoday.getTime();
    datetoday.setTime(timenow);
    thehour = datetoday.getHours();

    if (thehour > 20)
    display = “<?php bloginfo(‘template_url’); ?>/night.css”;
    else if (thehour > 17)
    display = “<?php bloginfo(‘template_url’); ?>/sunset.css”;
    else if (thehour > 14)
    display = “<?php bloginfo(‘template_url’); ?>/afternoon.css”;
    else if (thehour > 11)
    display = “<?php bloginfo(‘template_url’); ?>/noon.css”;
    else if (thehour > 7)
    display = “<?php bloginfo(‘template_url’); ?>/morning.css”;
    else if (thehour > 4)
    display = “<?php bloginfo(‘template_url’); ?>/sunrise.css”;
    else if (thehour > 1)
    display = “<?php bloginfo(‘template_url’); ?>/night.css”;
    else
    display = “<?php bloginfo(‘template_url’); ?>/sunset.css”;

    var css = ‘<’; css+=’link rel=”stylesheet” href=’ + display + ‘ \/’; css+=’>’;

    document.write(css);
    // End –>
    }

    Have noticed no flashing while loading.

  • Gerry

    Thanks Janet for taking the trouble to provide this tutorial.

    To those who choose to be so critical – if you know all this already, simply skip it and allows others to benefit without being made to feel inferior.

    • http://www.webcodepro.net/ Janet Wagner
      Author

      Hi Gerry – Thank you for your comments and I really appreciate the sentiment! Janet

      • http://www.deluxive.se Christopher Anderton

        I like the tutorial. Sometimes you NEED to use PHP instead of JavaScript. It all depends on how you gonna use it. Knowledge is power.

    • http://www.umbraprojekt.pl mingos

      Gerry, as noble as your comment is, I feel that correcting a mistake in the tutorial is necessary for those “others” not to face an unpleasant situation where they have a bug in their code and don’t know where to look for its source. It is not just criticism for the sake of criticism, as you appear to imply.

      • Tony

        Thanks for the corrections Mingos, the author has no problems being corrected and I for one appreciate your input as well

  • Hendra

    Rather than using different stylesheets, what do you think of using different classes and just do the conditional in the markup (for example in the body or the div wrapper) ?

  • http://www.web4you.co.in Deven

    Good stuff to get logic on how we can change the things using CSS and Javascript. Off course PHP should be there – Thank you.

  • http://www.blendwd.com/ Blend Web Design

    This is a brilliant article, thank you so much for suring.

    I am sure that we http://www.blendwd.com/ will get to use this on a new project in the very near future, we are very excited about trying it out.

  • Paul

    Is there a way, instead of using specific times, to specify sunset and sunrise, so that the code would automatically adjust for the length of daylight as the seasons change?

  • http://404am.blogspot.com astho

    nice idea…
    and use javascript?
    not always guarantee it will get the correct time, user system time could be wrong too.. ;)

  • Bill

    Thanx for the tutorial, Love the concept behind, It reminds me of the website of bechira sorin, but he probably use a random math function to change his bg

  • http://karlmac.com karl

    Great! I’ve always wanted to try this. Thanks for sharing!

  • http://twitter.com/theoinksty Gemma

    As usual, thanks for the tutorial, even if it is riddled with errors like a couple of people here have pointed out. It means I get to learn PHP better through debugging, which is a vital skill for any developer.

    To some of you who were criticising – criticise away, but try not to be so snobby about it please. You were beginners at one time, too.

  • http://www.scottcarmichael.co.uk/ Scott

    Nice tut, I made mine with a switch statement instead (but still the same simple idea)..

    switch ($time) {
    case 04 <= $time && $time < 09:
    echo "You're Up Early"; // 04:00am to 8:00am
    break;
    case 09 <= $time && $time < 12:
    echo "Good Morning"; // 9:00am to 12:00pm
    break;
    case 12 <= $time && $time < 18:
    echo "Good Afternoon"; // 12:00am to 06:00pm
    break;
    case 18 <= $time && $time < 22:
    echo "Good Evening"; // 06:00pm to 10:00pm
    break;
    case 22 <= $time && $time <= 03:
    echo "You're Up Late"; // 10:00am to 03:00am
    break;
    }