Supercharge Your CSS With PHP Under The Hood

Supercharge Your CSS with PHP Under the Hood

Cascading Style Sheets is a presentational style sheet language. In that sense, it does not have a lot of the functionality that many developers want to satisfy their programmer instincts. Today, we’re going to go over how to supercharge your CSS by putting some PHP under the hood.

Tutorial Details

  • Program: Apache, PHP
  • Version: n/a
  • Difficulty: Intermediate
  • Estimated Completion Time: 20 minutes

Introduction

Using CSS to power up a website is a requisite in the contemporary web for non-Flash websites – and for good reason. CSS is powerful. It can make or break a website (although usually IE6 is doing the breaking). Even with its usefulness, designers and developers alike have have wished for more out of the language since its inception over twelve years ago with the CSS Level 1 Recommendation. Today, we’re going to review some ways to Supercharge Your CSS With PHP Under The Hood.

Supercharging XHTML/CSS

Note: I am not going to be arguing for or against the concept of CSS Variable and/or CSS Constants. This article is written with the assumption that you will make an informed decision regarding these once presented with what it can do. This article teaches how to set them up and use them, but does not address the controversy in full.

Setting Things Up

Before the supercharging begins, we have to ensure that you have the proper requirements for doing so. We are going to go over two methods of making your CSS work with PHP, one that is short and sweet, and one that is a bit more elegant and less noticeable to the user. Both of these have the same basic requirement of a server running PHP. The more elegant version requires a bit more:

  1. Apache (running PHP, obviously)
  2. An editable .htaccess file

Setting Up the Simple Method

Web browsers are not that picky about file extensions when dealing with the HTML link tag. What they are picky about is the header data that it receives for that file. What that means is that you can link a *.php file with the proper header data in the place of a *.css file, and the browser will interpret the result just like standard CSS. To do so, add the PHP header that tells Apache to output the file as CSS:

<?php header("Content-type: text/css; charset: UTF-8"); ?>

Then, just link to the PHP file like you normally would:

<link rel="stylesheet" href="css/supercharged.php" media="screen">

Now that you have done this, you can–in theory–skip to the next section of the tutorial dealing with CSS variables and constants, if you would like; however, anyone who views your source is going to see that you have a PHP file where a CSS file should be. Additionally, just because the browser will interpret the result properly does not mean that it will necessarily do other things like caching the file in the browser. To fix this, we move on to the slightly more elegant version.

Setting Up the Elegant Method

Apache comes with a large number of .htaccess tricks. This is one of them. We are going to tell Apache to interpret all CSS files in a certain folder as PHP files, and the web browser (and your users) will, generally speaking, not know that you are doing so. First thing to do is to put the header data in your CSS file, just like the Simple Method:

<?php header("Content-type: text/css; charset: UTF-8"); ?>

Then, instead of saving the CSS file as a *.php file, you save it as a *.css file, and you place it in a folder for CSS (in our example, ~/css/). Once you have done this, create a *.htaccess file in that folder and add the following:

AddHandler application/x-httpd-php .css

This snippet tells Apache to interpret all CSS files in the folder with the *.htaccess file with the PHP script handler. If you do not have the ability to add this to a single folder or if you need this to be serverwide, you can also add this to the httpd.conf server configuration file for Apache. To do so, you would want to add the previous snippet right below the group of AddType and AddHandler declarations (like these from one of my servers):

AddType application/x-httpd-php .php .php3 .php4 .php5
AddType application/x-httpd-php-source .phps
AddHandler cgi-script .cgi .pl

Just remember that if you do add this to your httpd.conf server configuration file that EVERY *.css file on the server now must have the PHP header for text/css prepended to it. This is why my recommendation is to add it via .htaccess

Start the Engine with CSS Variables

From the Average Top 100 Weblog Performance Survey:

We ran a test on the top 100 blogs for external CSS files and total size. The average top 100 blog uses 4 external CSS files (@imports included) with an average total file size of 43.1K (uncompressed). The number of external CSS files ranged from 1 to 18. The total size of CSS ranged from to 0.2K to a whopping 307K. Note that this analysis does not include internal CSS within (X)HTML files. It does include nested CSS files called with @import directives.

That is a lot of CSS. Why is this? A lot of times it is because the CSS is being delivered uncompressed and not optimized. The more likely suspect is CSS bloat and poorly maintained code. One popular option to improving code maintainability is to implement CSS Variables through PHP.

What this means is that instead of having CSS like this (yes, this would produce an aberration of design, but it’s good at illustrating the point):

body {
 color: #000;
 background: #fff;
 font-size: 10px;
}
div#content {
 background: #ccc;
 font-size: 1.1em;
}
div#sidebar {
 color: #fff;
 background: #000;
 font-size: 1.0em;
}
div#footer {
 color: #555;
 background: #ccc;
}

You could have CSS like this:

<?php
$primaryTextColor = '#000';
$secondaryTextColor = '#fff';
$tertiaryTextColor = '#555';
$primaryBGColor = '#fff';
$secondaryBGColor = '#ccc';
$tertiaryBGColor = '#000';
$primaryTextSize = '10'; //pixels
?>
body {
 color: <?=$primaryTextColor?>;
 background: <?=$primaryBGColor?>;
 font-size: <?=$primaryTextSize?>px;
}
div#content {
 background: <?=$secondaryBGColor?>;
 font-size: <? echo 1.1*$primaryTextSize ?>px;
}
div#sidebar {
 color:  <?=$secondaryTextColor?>;
 background: <?=$tertiaryBGColor?>;
 font-size: <?=$primaryTextSize;?>px;
}
div#footer {
 color: <?=$tertiaryTextColor?>;
 background: <?=$secondaryBGColor?>;
}

Note that the long variable names is for illustration purposes only. Obviously, these variables can be as long as or as short as you like, and shorter variables make for smaller file sizes.

In the example above, we have used basic variables to set up a monochrome color scheme that could then be used throughout the website in other styles. These variables could easily have been interchanged with $color01, $color02, $color03, etc to produce similar effects. Often, designers and front-end web developers get asked by clients “Hey, can you make all of the text a little darker?” or “Can you make all of the text just a little bigger?” While using variables like this will not always be the best solution, it often would reduce the maintenance time when using many templating systems and blogging platforms (WordPress, Moveable Type, Expression Engine, etc) or corporate CMSes (Drupal, Joomla, Bitrix, etc).

An alternative method of storing the variables is to store the data in associate arrays (which is my preferred method), which produces code more like the following:

<?php
$defaultCSS = array(
 'color01' => '#000',
 'color02' => '#fff',
 'color03' => '#ccc',
 'color04' => '#555',
 'baseTextSize' => '10'
);
?>
body {
 color: <?=$defaultCSS['color01']?>;
 background: <?=$defaultCSS['color02']?>;
 font-size: <?=$defaultCSS['baseTextSize']?>px;
}
div#content {
 background: <?=$defaultCSS['color03']?>;
 font-size: <? echo 1.1*$defaultCSS['baseTextSize']; ?>px;
}
div#sidebar {
 color:  <?=$defaultCSS['color02']?>;
 background: <?=$defaultCSS['color01']?>;
 font-size: <?=$defaultCSS['baseTextSize'];?>px;
}
div#footer {
 color: <?=$defaultCSS['color04']?>;
 background: <?=$defaultCSS['color03']?>;
}

Calculations in CSS

Once you have set things up for using PHP with your CSS, you can then do some neat things like calculations. Let’s assume that you want to set up a system in you provide a bunch of DIVs on screen, each with a different type of element inside. Each element type (i.e. img, p, blockquote, etc) has a unique height and width controlled via CSS, and you want the amount of margin to be based off these values like so:

Diagram of Padding / Element Measurements

In this scenario, you want to set up a standardized grid that contains three different types of elements (img, p, and blockquote) encapsulated in two different containers (div and li). Every DIV has to be 550px wide and 250px tall, every LI has to be 600px wide and 300px tall, and each of the element types has a different height and width. The positioning of the elements on the inside must be dead center. Over time, the heights and widths of the different DIVs/LIs and elements will likely need to be changed. You could manual enter the amount of margin for each of the different elements and/or use extra class information on the container DIVs to add the appropriate amount of padding, but this is not that useful for quick changes, like those wanted by someone who is prototyping in the browser or who has 200 of these different elements for which they would have to modify data.

Step 1 – The Structure

First, we set up the XHTML content that we are going to style like so:

<div><p>Lorem ipsum dolor sit amet tellus.</p></div>
<div><blockquote>Etiam quis nulla pretium et.</blockquote></div>
<div><img src="images/inset.png" alt="Inset Image" /></div>
<ul>
<li><p>Lorem ipsum dolor sit amet tellus.</p></li>
<li><blockquote>Etiam quis nulla pretium et.</blockquote></li>
<li><img src="images/inset.png" alt="Inset Image" /></li>
</ul>

Step 2 – The PHP Header and Variable Declarations

Next, we set up the PHP/CSS file that we are going to use to style the XHTML. This is where we declare the standard sizes of the different elements for use throughout the page.

<?php
header("Content-type: text/css; charset: UTF-8");

$divData = array(
 'width' => '550',
 'height' => '250',
);
$liData = array(
 'width' => '600',
 'height' => '300',
);
$blockquoteData = array(
 'width' => '440',
 'height' => '100'
);
$imgData = array(
 'width' => '450',
 'height' => '150'
);
$pData = array(
 'width' => '480',
 'height' => '130'
);
?>

Step 3 – The CSS with Variables and PHP Calculations

Next, we continue the PHP file from Step 2 and utilize the variables that we set in calculations. Additionally, we set the calculated MarginX and MarginY values of the different elements to reduce the number of calculations necessary.

div {
 width: <?=$divData['width']?>px;
 height: <?=$divData['height']?>px;
}
li {
 width: <?=$liData['width']?>px;
 height: <?=$liData['height']?>px;
}
div blockquote {
 width: <?=$blockquoteData['width']?>px;
 height: <?=$blockquoteData['height']?>px;
 <?
  $blockquoteData['divMarginX'] = $divData['width']-$blockquoteData['width'];
  $blockquoteData['divMarginY'] = $divData['height']-$blockquoteData['height'];
 ?>
 margin: <? echo blockquoteData['divMarginY']/2; ?>px <? echo blockquoteData['divMarginX']/2; ?>px;
}
div img {
 width: <?=$imgData['width']?>px;
 height: <?=$imgData['height']?>px;
 <?
  $imgData['divMarginX'] = $divData['width']-$imgData['width'];
  $imgData['divMarginY'] = $divData['height']-$imgData['height'];
 ?>
 margin: <? echo imgData['divMarginY']/2; ?>px <? echo imgData['divMarginX']/2; ?>px;
}
div p {
 width: <?=$pData['width']?>px;
 height: <?=$pData['height']?>px;
 <?
  $pData['divMarginX'] = $divData['width']-$pData['width'];
  $pData['divMarginY'] = $divData['height']-$pData['height'];
 ?>
 margin: <? echo pData['divMarginY']/2; ?>px <? echo pData['divMarginX']/2; ?>px;
}
li blockquote {
 width: <?=$blockquoteData['width']?>px;
 height: <?=$blockquoteData['height']?>px;
 <?
  $blockquoteData['liMarginX'] = $liData['width']-$blockquoteData['width'];
  $blockquoteData['liMarginY'] = $liData['height']-$blockquoteData['height'];
 ?>
 margin: <? echo blockquoteData['liMarginY']/2; ?>px <? echo blockquoteData['liMarginX']/2; ?>px;
}
li img {
 width: <?=$imgData['width']?>px;
 height: <?=$imgData['height']?>px;
 <?
  $imgData['liMarginX'] = $liData['width']-$imgData['width'];
  $imgData['liMarginY'] = $liData['height']-$imgData['height'];
 ?>
 margin: <? echo imgData['liMarginY']/2; ?>px <? echo imgData['liMarginX']/2; ?>px;
}
li p {
 width: <?=$pData['width']?>px;
 height: <?=$pData['height']?>px;
 <?
  $pData['liMarginX'] = $liData['width']-$pData['width'];
  $pData['liMarginY'] = $liData['height']-$pData['height'];
 ?>
 margin: <? echo pData['liMarginY']/2; ?>px <? echo pData['liMarginX']/2; ?>px;
}

What this allows us to do now is to change the size of elements once at the top of the file and not recalculate 12 margin values (24 if the margin values were asymmetric). Understand that I am not suggesting this will be used in every one of your projects going forward, but this kind of technique has definite advantages over the standard “static” CSS method.

Shrink that CSS

As mentioned earlier, CSS can get pretty big. One thing that you can do to reduce CSS size is to automatically gzipping your CSS files. To do this, you have two options on how to do so: straight from Apache using mod_gzip / mod_deflate or use PHP’s built-in compression methods, which we’ll do here.

Step One – Set Up The Gzipping Snippet

Inside of our CSS file, we already have a snippet of PHP that sets up the header:

<?php header("Content-type: text/css; charset: UTF-8"); ?>

All we have to do now, is add a single line of code setting an output buffer to use ob_gzhandler before the header declaration like so:

<?php
ob_start("ob_gzhandler");
header("Content-type: text/css; charset: UTF-8");
?>

It should be noted that there are other ways of doing gzip compression and they all have their benefits and shortcomings. My preferred method is using mod_deflate as mentioned earlier, but not all designers and developers have that option.

If($usingPHP==TRUE) { return ‘Happiness’; }

Adding programming logic to a style sheet language is nothing new. Many websites determine what stylesheets they use based on URL, login status, or even the date. Here’s a simple example that can be applied easily to blogs and e-commerce sites (amongst others). Let’s assume that you have a h1 tag that is replaced using the Phark image replacement method described by the following CSS:

h1 {
 width: 300px;
 height: 80px;
 text-indent: -9999px;
 background: url(images/logo.png) no-repeat;
}

By adding a little PHP in the mix to determine the date when the CSS is loaded, you can then specify a different image for a holiday like Google often does with its Google Doodles (although they use a different technology solution to do so):

<?php
 $month = date('m');
 $day = date('d');
 if($month=='12' && $day=='25') {
 	$logoSrc = 'images/holidayLogo.png';
 } else {
 	$logoSrc = 'images/logo.png';
 }
?>
h1 {
 width: 300px;
 height: 80px;
 text-indent: -9999px;
 background: url(<?=$logoSrc?>) no-repeat;
}
Normal Logo becomes Holiday Logo

This is just a super simple example. Your CSS is just waiting to be amped up by PHP. What you do with it can vary from person to person. One of my personal uses is to use it as a way of obscuring and embedding @font-face files using data URI strings and checking the referer requesting the file similar to parts of the technology that Typekit uses:

<?php
// This function grabs the file and converts it to a URI string
function data_url($file, $mime) {
 $contents = file_get_contents($file);
 $base64 = base64_encode($contents);
 return ('data:' . $mime . ';base64,' . $base64);
}

$checkReferer = $_SERVER['HTTP_REFERER'];
$checkMatch = preg_match('/yourdomain\.com/',$checkReferer);
if($checkMatch) {
?>
 @font-face {
   font-family: FontName;
   src: local("FontName"), url(<?php echo data_url('FontFileName.otf','font/otf'); ?>) format("opentype");
 }
<?php
} else {
 /* This @font-face asset is unavailable */
}
?>

CSS Variable Controversy

Using variables in CSS, no matter the pros and cons has been a controversial issue for years. Like I said at the beginning of this article, I am not going to argue for or against the concept of CSS Variables or CSS Constants. Some very respected designer and developers have argued against it, while others have argued for it. I hope, for the sake of a better web, that an effective CSS-only solution happens sooner than later. In the meantime, those of us who support CSS variables and constants can rely on our server-side languages while those who do not support them will simply continue on as normal.

What Ideas Can You Come up With?

I’m always on the lookout for new and innovative ways to supercharge my CSS with PHP. What are some of your favorite use-case scenarios for mixing CSS with PHP?


Add Comment

Discussion 70 Comments

Comment Page 1 of 21 2
  1. Zack says:

    This is very interesting. ive always wondered if there was a way to use variables with css. well here is a way. looks like a great post but ill have to read it more thoroughly later.

  2. As you noted about the controversy, I won’t ever be using this method. But detailed tutorial none the less.

    Plus has the sidebar of NETTUTS has dropped down and there’s quite a few style issues going on?

    • Jeffrey Way says:
      Staff

      No – just an extra closing div in the markup that I had to hunt down quickly. :)

      • That’s not as bad as my poorly contructed sentence – “Plus has the sidebar of NETTUTS has dropped down and there’s quite a few style issues going on?”

        To redeem myself – Plus, has the sidebar of NETTUTS dropped down? There is also quite a few style issues going on?

        :D

  3. This method has a purpose, but this tutorial doesn’t really touch on it. I’d use this method to generate CSS files with variable arguments. When you hardcode the variable values in the PHP file, you are not really using the right tool for this job. Have you looked at Compass? There are other tools like it too.

  4. 青柠檬 says:

    wow,i knows many things from this website.

  5. Chad Hietala says:

    Great tutorial. I don’t plan on using this method but I like keeping the mindset of OOP when doing CSS. Jeff Croft wrote about bringing the OOP mindset into CSS here http://jeffcroft.com/blog/2009/may/20/applying-oop-concepts-css/

    • kaiser says:

      And THIS was the only really good answer to php-stylesheets and programs(!) that give you a new language to write another easier (how st*pid ist that?) … when you use css-libraries like blueprint then you´ll all get the point pretty fast: css-classes are “reverse”-constants > you define them in css and you them in your php over and over again.

  6. adrusi says:

    this gives you all the things that SASS (http://lab.hamptoncatlin.com/play/with/sass) does except nested css elements

  7. Mustardamus says:

    And if you are on Ruby LESS (http://lesscss.org/) is a must! Plays nice with Rails too via the plugin (http://github.com/augustl/less-for-rails/tree/master).

    Interesting article anyway, no question.

  8. There is an other possibility to fix the caching issue, even without modifying httpd.conf / .htaccess. Simple put the following code on top of your “PHPified CSS”:

    $lastModified = filemtime(__FILE__);
    $etagFile = md5_file(__FILE__);
    $ifModifiedSince=(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false);
    $etagHeader=trim($_SERVER['HTTP_IF_NONE_MATCH']);

    header(“Last-Modified: “.gmdate(“D, d M Y H:i:s”, $lastModified).” GMT”);
    header(“Etag: $etagFile”);
    header(‘Cache-Control: public’);

    if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $lastModified ||
    $etagHeader == $etagFile)
    {
    header(“HTTP/1.1 304 Not Modified”);
    exit;
    }

    This will do the job as it checks the etag and the modified-since header. If the copy is still fresh, a “304 not modified” will be sent.

  9. James Robertson says:

    Interesting way of doing it – thanks of sharing.

    I currently use DTCSS – http://code.google.com/p/dtcss/ – uses pre-processing and has a neat caching system.

  10. Xaver says:

    Really nice article! I prefer to remove whitespace and cache the data as well

  11. Wish you showed a demo instead of just picture’s.

  12. I liked it, very useful.

  13. Milan says:

    Was looking for this yesterday. Thanks for sharing.

  14. Cory says:

    “We ran a test on the top 100 blogs for external CSS files and total size. The average top 100 blog uses 4 external CSS files (@imports included) with an average total file size of 43.1K (uncompressed). The number of external CSS files ranged from 1 to 18. The total size of CSS ranged from to 0.2K to a whopping 307K…”

    Damn thats really sad. At only 8-12k I start feeling like I have way to much and try to go back and remove/merge classes. Goes to show how few people ACTUALLY know css.

  15. awake says:

    mike,

    is this similar to LESS for ruby?
    in the sense that it allows you put variables into your css file?

    • IgnacioRV says:

      As some commented up here, Less, Sass and Compass are a bit more complex because they let you not only to use variables, but also add nested rules, operations and mixins…

      But if you are only asking about css variables, then yes, they are pretty similar.

  16. dwainehead says:

    Interesting, makes me want my own interface to edit on my site with….

  17. Now, that is one steep learning curve for me today!

  18. Vikas says:

    Thank for this information.. its really very usefull

  19. IgnacioRV says:

    This is quite interesting, but for now I prefer to keep my css files as small and simple as possible. Especially when they have to be readable for designers who doesn’t know anything about programming.

    Until now, I have solved almost all css coding problems using multiple classes… but.. who knows?, maybe this can be usefull for a later project ^^

  20. Lane says:

    One question. What extension do you give the css file if you are planning on using PHP inside it?

    Also, I think line 14 of the Christmas example is missing the php tags.

    #14 background: url($logoSrc) no-repeat;

    • Author

      You can use either the .php or .css extension, depending on how much configuration you choose to do via .htaccess and/or httpd.conf

      As far as the example, you’re correct. The line should read:

      background: url(‘<?=$logoSrc?>’) no-repeat;

  21. Patrick says:

    Nice way for an automated css system.

    I think it would be a great idea to include expire-header here, because it can decrease servertraffic.

  22. David Moreen says:

    Regardless of how cool this is, I don’t see myself using it unless a client strictly specifies this option.

  23. Danc Chan says:

    Wow, guess this is more hardcore than the norm. Quite interesting, but I don’t think I am going to use this method. Sorry for that. ^^

  24. Amir says:

    Nice article, Thanks

  25. I’ve been working on project like this for a long while now, CSScaffold, except it all happens transparently and doesn’t use PHP inside the CSS, instead it extends CSS.

    http://wiki.github.com/anthonyshort/csscaffold

    - Constants
    - Mixins
    - Nested Selectors
    - Expressions
    - Caching and gzipping
    - Extendable through plugins

    Built it so I could use all the goodies of SASS with my PHP projects. It’s essentially what you’ve done above, but more developed and cleaner :)

  26. Markus says:

    There’s one point I totally disagree with you: the long vs. short variable names note.

    The .php file won’t be transfered to the user so file size isn’t an issue here. It’s better to use talking names and those are most of the time rather long. This is one of the first things they tell you in software engineering classes “don’t name your variables a,b,c..”

    If you use associative arrays for all of your stuff, you loose the ability to use syntax completion in your IDE.

    • Author

      Realize that when I said the long variables were for illustrative purposes only, I still advocate using descriptive variable names.

      As far as IDE syntax completion, I use emacs or jEdit for 90%+ of my coding with syntax completion generally off or unavailable. Syntax completion is not usually something for which I tailor my code. This falls into the realm of personal preference, and I don’t prefer it.

  27. Tony says:

    I would just like to point out that by writing this article, you are in fact arguing in favour of CSS variables. What you really mean is that you are not going to forcibly argue in favour of CSS varibles. It would be akin to me saying that I don’t mean to split hairs, when in fact I am purposely making a petty distinction!

  28. Martyn Web says:

    Is this something I should really consider to be important in the future of web design and start to implement this in my designs?

    Interesting Article tho!

    • Yes, you really should! I think it’s sad that he does not mention that using PHP you can make the browsers cache your static content, such as images, javascript, css etc. By doing this you can reduce load and render times for the user A LOT!

      • Sam Tresler says:

        Actually, no, php cannot do that for you. The browser cache is on the browser end and can’t be controlled by the server for VERY good security reasons. If you could, that would be a browser bug.

        I strongly disagree with this article as I have yet to see anything that this methodology implements that cannot be done in a template and clean css, plus this breaks the design/functionality barrier. Also, the #1 designer complaint so far that I hear is that designers want less php not more.

        I appreciate that the author took the time to make a detailed tutorial, but in my opinion this is just incredibly bad coding style.

  29. Michael says:

    Great article! A lot of neat ideas here. Isn’t PHP just great?

  30. I use PHP to put multiple CSS files together, too reduce the number of http requests, minify the CSS, and then gzip and output. I mainly have have a “loader.php” file in my style folder and redirect images-, javascript- and css files to that file and from there I do all the minification and gzippin’ etc.

  31. Diego SA says:

    Oh shut up! This is so f…ing much awesome and useful! Next website will have it!

  32. Simon says:

    I experimented with this for a recent project (javascript as well actually), and it’s extremely useful, but can get a bit messy.

    Thanks for the tutorial. I’ve bookmarked it for future use.

  33. Zy says:

    Well I personally think, that this technique is a waste of time :)

    If we think from logic side of the deal, then we see, that regular coding is way faster than writing PHP stuff, remember syntax and etc.

    For example I’m a TextMate user, where is code snippets combined with a great editor. So no need to type again and again same values and/or statement blocks. Way faster than I could think of something else :)

    Talking about possibility to change CSS values on the fly… think about after-service support :) Why bother regular user about design / coding stuff :)

    Useless.

  34. David B. says:

    Excellent article on the power of PHP + CSS. When designing, I’ve had so many situations where CSS variables would’ve saved a ton of work. This was the solution for me.

    Again, very well done – Though I will say I cringed a bit at “text-indent: -9999px; ” :D Ewwwww, haha.

  35. Adam says:

    I have been using this method for several years now and am incorporating into in my soon to be released CMS system (www.mybolmanager.com). My method is similar to this post but goes a little further in that you can define rules targeted specifically to various browsers and Operating Systems (or combinations of). No more hacks needed… for example:

    /* win ie6
    body {
    background: red;
    } */

    /* FF3
    body {
    border: 2px solid #000;
    } */

    My css parser then simply removes the comments that match the environment and I now have a css file being served that is targeted to that environment without having to introduce hacks (such as box model).

    A lot of my settings are stored in a config.ini file for ease of maintenance.

    It really makes my development time very quick!

  36. peqpe says:

    Great! :)
    I wondered if this could be possible for years :D
    Thanx ;)

  37. Definitely think this is a very long winded coding method that would take a long time to setup and code for very little benefit.

    I personal gzip & merge css (and javascript) files on the fly using php which saves a lot of time and doesn’t try to reshape the way we code. There are so many handy CSS editors that make writing CSS so easy (ie Coda).

    The script I use for gzipping and merging can be found at:
    http://thewebdevelopmentblog.com/2008/10/tip-speed-up-your-websites-using-gzip-and-merging-files/

  38. skylar says:

    CSS is already OO (in a way), things like this:
    # $primaryTextColor = ‘#000′;
    # $secondaryTextColor = ‘#fff’;
    # $tertiaryTextColor = ‘#555′;
    # $primaryBGColor = ‘#fff’;
    # $secondaryBGColor = ‘#ccc’;
    # $tertiaryBGColor = ‘#000′;
    # $primaryTextSize = ’10′; //pixels

    would be inherited through a base class, so you don’t need to pass around variables into styles.

    but none the less this is the best approach i’ve seen to using php/css

  39. Alex Weber says:

    Excellent tutorial! I can’t wait to try this out in a project sometime soon!

  40. Kris Khaira says:

    Using the term “corporate CMSes” to refer to Drupal, Joomla and Bitrix is a bit misleading when they have been used for so many non-commercial websites. That aside, this is quite a helpful tutorial.

  41. Beck says:

    AMAZING! Really really really thanks! I have learned a lot from this! This technique
    have very big potential!

  42. Beck says:

    Tutplus worth to subscribe! Jeff’s tutorials are awesome as well.

  43. feeling says:

    现在才发现英语是多么重要,从事计算机工作不会英语是多么痛苦的事情啊!

  44. Sean Lum says:

    Haha yeah, normally when I code my CSS files I like to keep them under 10k. I mean, if you know how to do complete hierarchy levels it really saves space and chars on your code. I don’t really use classes at all anymore, unless it is topic specific. Considering how they are getting kind of redundant, its better when you can call on a inherit element rather than going #id.class when you can just go #id element. It also makes the xhtml look sooo much cleaner.

    I wish people would not stop at learning CSS, but keep going till they master it and write super optimized code. When you have over 12k of CSS that is uncompressed, it gets hairy.

    This was a great tutorial, nice and optimized, I can’t wait to start implementing these techniques ^^ thanks for the share.

    This reminds me of Litestep theme creations (Litestep is a shell for windows with VC++ as the code) and how people utilize globals.rc and then call upon them in the other documents. Makes things much nicer.

    I wonder what this implementation would look like with some HTML5, jQuery, and PHP :]

  45. antpaw says:

    for more comfort check out xCSS http://xcss.antpaw.org/ !

  46. eebrah says:

    Love the tutorial, really got me to start thinking about my CSS. Plus sparked me into researching GZipping my pages.
    The sites I’m designing are now lighter, my users thank you

  47. Richard Lynch says:

    “Note that the long variable names is for illustration purposes only. Obviously, these variables can be as long as or as short as you like, and shorter variables make for smaller file sizes.”

    Not sure why you added the bit about variable name length and filesize… That’s the filesize of the server-size PHP, and does not have any meaning to the front-end, which is going to get the CSS output.

  48. Andrea Puddu says:

    Amazing, thanks for the trick!!!

  49. Michael Bryan says:

    I’ve used this method in projects before, but very rarely. Typically I do it when the user wants to control some css elements without actually coding anything. I’ve only needed to do it twice and didn’t enjoy it either time.

  50. Bugsy says:

    I love using this method when building a site when I’m still deciding on colors and padding. Once I have it dialed in I just pull up the CSS in my browser and copy and paste it back into a new .css file and change it from style.php to style.css. I switch back to style.php when I’m making edits of additional tweaks.

Comment Page 1 of 21 2

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.