dynamic CSS background images


/ Published in: PHP
Save to your folder(s)

dynamic CSS file, where the background style attributes (in this case h2 headers) are auto-created from the files in a particular directory.

1. include the css file as per normal in your
2. create new css.php file
3. add in custom css header - header("Content-type: text/css");
4. create directory full of heading images
5. add in code below
6. will automatically set the background image of "some-header.png" from the image directory
6. win life!


Copy this code and paste it in your HTML
  1. <? header("Content-type: text/css"); ?>
  2.  
  3. /* all your other CSS rules can go here too! */
  4.  
  5. h2 {
  6. display:block;
  7. width:400px;
  8. height:30px;
  9. background-repeat:no-repeat;
  10. }
  11.  
  12. h2 span {
  13. display:none;
  14. }
  15.  
  16. <?
  17. $path = 'headers/';
  18. $dir = $_SERVER['DOCUMENT_ROOT'] . $path;
  19. if ($handle = opendir($dir)) {
  20. while (false !== ($file = readdir($handle))) {
  21. if ($file != "." && $file != "..") {
  22. $class = current(explode('.', $file));
  23. echo 'h2.' . $class . ' { ' . "\n";
  24. echo 'background-image:url("' . $path . $file . '"); ' . "\n";
  25. echo '}' . "\n\n";
  26. }
  27. }
  28. closedir($handle);
  29. }
  30. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.