Working with CSS Sprites & PHP

A CSS sprite is a single image that contains many images images that you want to display on the page. By using the background position properties of an element we can select a specific image from a single one. The reason we do this is to load multiple images without having to make multiple HTTP requests. Thus speeding up the performance of our page.

Take a look at the CSSsprite library over on github:

https://github.com/arzynik/CSSsprite

First lets make an array of our images. Each image array needs a file and can have an array of style attributes.

$images['devin']['file'] = 'devinsmith.logo.png';
$images['devin']['style']['margin'] = '0 auto';

Next we'll create our sprites with the CssSpriteMap class

$sprite = new CssSpriteMap();
$sprite->setImages($images)
  ->setInPath('./')
  ->setForceRefresh(false)
  ->setCssPrefix('csssprite')
  ->setOutPath('./cache/')
  ->setOutUrl('cache/')
  ->create();

Now that we have our object all set up we can now use it in a simple webpage.

<style><?=$sprite->getCss()?></style>
<div class="<?=$sprite->getImg('devin')->getCssPrefix()?>devin"></div>