Creating valid cross-browser CSS using PHP
Every webdesigner or -programmer knows it is usually necessary to give special care to some specific browsers when making an interface cross-browser compatible. In the case of Internet Explorer 6 having no extra measures is an exeption. Luckily Internet Explorer 7 behaved better and 8 even more so, but still there is their annoying older who will be around for some time to come.
Solutions range from completely seperate stylesheets for every single browser or conditions or hacks to make certain parts of a stylesheet readable only by a specific browser. The former forces you to check which browser is used on every page load and the latter will likely cause your css to become invalid.
The solution I prefer takes advantage of the way CSS is interpreted. You should understand that CSS is read from top to bottom and the latest declarations are applied. So if you have 2 “color” declarations for one selector the latest declaration will be applied.
For more information on stylesheets visit the CSS section at w3schools.com.
I use PHP to output the CSS we need depending on the browser. This means I only have to call one PHP-generated stylesheet, and have the browser specific attributes in seperate .css files. I usually put the .css files in a folder called “layout/”, this example is no different. The .php file (style.php) should be in the same folder as your .css files.
<link href="layout/style.php" rel="stylesheet" type="text/css" />
As you can see it is linked to the page the same way as other external stylesheets.
The PHP code is very simple but effective. First it identifies its content as CSS using the header() function and loads the content of my main stylesheet (style.css). It then checks to see if the browser is Internet Explorer. The last check is to make sure the version of Internet Explorer is 6 or lower, and that the IE6 specific stylesheet (style_ie6.css) exists. If that is all true it loads the IE6 specific stylesheet. This stylesheet only contains the classes and attributes that differ from the main stylesheet.
The code is as follows:
<?php
header("Content-type: text/css");
include 'style.css';
$agent = $_SERVER['HTTP_USER_AGENT'];
if (eregi("msie",$agent) && !eregi("opera",$agent))
{
$val = explode(" ",stristr($agent,"msie"));
$version = explode(".",$val[1]);
if ($version[0] <= 6 && file_exists('style_ie6.css'))
{
include 'style_ie6.css';
}
}
?>
If you also have a .css file for another browser, you can simply add more checks for those specific browsers.
Feel free to comment if you have any questions or remarks about this post.
Tagged with CSS, PHP , No Comments