Convert nested PHP array to CSS string

This function will convert a PHP array of nested CSS selectors into a CSS string. Nesting comes in handy with SASS rules or nesting standard CSS within media queries.

<?php

/**
 * Converts a multidimensional array of CSS rules into a CSS string.
 *
 * @param array $rules
 *   An array of CSS rules in the form of:
 *   array('selector'=>array('property' => 'value')). Also supports selector
 *   nesting, e.g.,
 *   array('selector' => array('selector'=>array('property' => 'value'))).
 *
 * @return string
 *   A CSS string of rules. This is not wrapped in <style> tags.
 */
function grasmash_generate_css_properties($rules, $indent = 0) {
  $css = '';
  $prefix = str_repeat('  ', $indent);

  foreach ($rules as $key => $value) {
    if (is_array($value)) {
      $selector = $key;
      $properties = $value;

      $css .= $prefix . "$selector {\n";
      $css .= $prefix .grasmash_generate_css_properties($properties, $indent + 1);
      $css .= $prefix . "}\n";
    }
    else {
      $property = $key;
      $css .= $prefix . "$property: $value;\n";
    }
  }
  return $css;
}
?>

Example usage:

<?php
$nested_css_rules = array(
  '@media (min-width: 44em)' => array(
    '.special-class' => array(
      'width' => '50px',
      'color' => 'red',
    ),
  ),
);
print "<style type='text/css'> \n" . grasmash_generate_css_properties($nested_css_rules) . "</style>\n";

$flat_css_rules = array(
  '.special-class' => array(
    'width' => '50px',
    'color' => 'red',
  ),
);
print "<style type='text/css'> \n" . grasmash_generate_css_properties($flat_css_rules) . "</style>\n";
?>

These examples will output:

<style type='text/css'>
@media (min-width: 44em) {
  .special-class {
      width: 50px;
    color: red;
  }
}
</style>

<style type='text/css'>
.special-class {
  width: 50px;
  color: red;
}

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.