Prefix CSS-selectors PHP Class
Published Thursday, April 24, 2008 in CSS, Development, PHP
Recently at work I had to combine a site's existing design and a PHPBB-template.
If you've ever worked with PHPBB (front or back-end) you'll know it's no dream.
The hardest part with combining PHPBB (or any other third-party-software) with your own code is to make sure your CSS-rules (well JS as well I suppose) don't collide.
PHPBB styles h1:s, you style h1:s, PHPBB styles a:s, you style a:s. It's a right mess when both are trying to style elements on such a general level.
As most websites nowadays, most of PHPBB's themes has a wrapper-div around the entire website so I had an idea to manipulate all of PHPBB's CSS-code before output and add that wrapper-div's ID-name in front of every selector.
So instead of PHPBB styling all the h1:s in a document, it would only style (in this case) #wrap h1:s (#wrap is the name of the wrapper-div in the prosilver-theme).
Recent versions of PHPBB include a similar type of CSS-compression as I've explained before in CSS compression and constants PHP-class so you have access to every line of CSS code in a variable before it's outputted. The merging of CSS happens in PHPBB3/style.php. Look at the very bottom and you'll see something like echo $theme['themedata']; The themedata-index in the $theme-array is what contains all of the CSS for that theme. What you want to do here is run my function on that variable before output:
So instead of:
echo $theme['theme_data'];
You want:
require_once 'CSSSelectorPrefixer.php';
echo prefixCSSSelectors($theme['theme_data'], '#wrap');
The function will then add #wrap at the beginning of every selector in the string.
One problem with this though is that #wrap isn't the root-element of the document, the html-element is. So any styling on body or html will have no effect as they will be changed to #wrap body and #wrap html. I believe this is what you want in most cases as you've probably styled both elements in your own CSS.
The function will also remove duplicate #wrap:s (if the PHPBB-style contained something like #wrap a the function will turn it in to #wrap #wrap a, but before it returns the new code it will remove all duplicate #wrap:s (or whatever you set)).
This really simplified the design-move and hopefully it will help someone looking to do the same thing.
You can as usual get the code from my Google Code repository.
Laters





