
Using PHP & CSS to change the style of a Webpage
In one of my previous posts on CSS Guide, I had discussed about how different style values can be implemented dynamically with php on the basis of user input. Today we will be moving a step further & we will utilize the power of the PHP date() function to dynamically change the embedded stylesheets on the basis of the local system clock time. We are gonna make three separate stylesheets each containing different values for the different elements of our webpage. The main funda is, we intend to change the look of our web pages,automatically, on the basis of variation in time viz. morning, day & night.
We just need to put a simple, few lines of PHP code in the css style tag of every web page that we wish to update automatically. Additionally we need to create 3 separate stylesheets for morning, day & night (viz morning.css, day.css & night.css). Primarily, the 3 styles sheets will hold different values for the same elements of a web page, while additional properties can be imparted to any or all of them as per your freedom of choice. There is no barrier to the amount of changes we can perform to a web page through stylesheets.
However in this sample code, I will be using a limited set of elements for all my stylesheets. But you are always free to tweak your primary stylesheet & you can even change the whole website layout automatically with the variation in time.
Step 1
Following is a sample code for a webpage which contains the php enabled css declaration in the <head> section:
<html>
<head>
<link rel=”stylesheet” type=”text/css” media=â€screen†href=”<?php
$hour = date(“H”); //PHP date() function fetching the current hour on local machine
if ($hour < 12)Â Â Â Â Â Â //if time is below noon(12pm)
{
echo “style/morning.css”;
}
elseif ($hour < 17)Â //if it is afternoon(greater than 12 but below 5)
{
echo “style/day.css”;
}
else
{
echo “style/night.css”; // if it is evening or night
}
?>” />
</head>
<body>
<p>Hello World!</p>
</body></html>
Step 2 Sample Style for morning(morning.css)
p {
color:#008400;
}
Similarly create other styles for day & night. Your website will change its look on the basis of the local system time.
You might also like:
- Creating Dynamic Stylesheets with PHP – Part 1
- CSS Tricks for Dummies!
- CSS Frameworks
- Faster loading web pages (Good for everyone)
- How to Track Clicks on Outgoing Links
Tags: css tutorial, date function, php css, php tutorial




