Skip to content

Instantly share code, notes, and snippets.

@matula
Last active December 10, 2015 15:29
Show Gist options
  • Save matula/4454829 to your computer and use it in GitHub Desktop.
Save matula/4454829 to your computer and use it in GitHub Desktop.
A simple PHP function that take an array of CSS values and puts them into relevant media queries
<?php
function parseCss($css = array()) {
// Init
$return = array();
// Set the break points here
$return['default'] = '';
$return['tablet'] = '@media only screen and (max-width : 1024px) {';
$return['phone'] = '@media only screen and (min-width : 320px) and (max-width : 480px) {';
// Loop and append
foreach ($css as $css_key => $css_value) {
$return['default'] .= $css_key . '{';
if (is_array($css_value)) {
foreach ($css_value as $ak => $av) {
if (is_array($av)) {
$return[$ak] .= $css_key . '{';
foreach ($av as $k => $v) {
$return[$ak] .= $v . ';';
}
$return[$ak] .= '}';
} else {
$return['default'] .= $av . ';';
}
}
} else {
$return['default'] .= $css_value . ';';
}
$return['default'] .= '}';
}
// @TODO - make this so you don't have to update everytime you add a breakpoint
return ($return['default'] . $return['tablet'] . '}' . $return['phone'] . '}');
}
/*
* USAGE
*/
// variables
$blue = '#009';
// mixin -- kind of a hack, since duplicate keys can't be added in array
$border = array (999999 => 'border: 2px solid #676');
$css = array (
'h1, h2, h3' => 'color: #449',
'#content' => array (
'width: 800px',
'margin: 0 auto',
'background: #dd9',
'tablet' => array (
'background: red',
) + $border,
'phone' => array (
'background: ' . $blue,
'width: 100%',
'border: 2px solid #090',
'color: #fff'
),
),
'a' => array (
'color: #069',
'text-decoration: none'
),
'a:hover' => array (
'text-decoration: underline'
),
);
// If you send the 'compress' querystring
if (isset($_GET['compress'])) {
ob_start ("ob_gzhandler");
header("Content-type: text/css; charset: UTF-8");
header("Cache-Control: must-revalidate");
$offset = 60 * 60 ;
$expire = "Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
header($expire);
} else {
header('Content-type: text/css; charset: UTF-8');
}
print(parseCss($css));
/*
* In the HTML file
*/
?>
<link rel="stylesheet" type="text/css" media="screen" href="css.php">
<!-- or if compressed -->
<link rel="stylesheet" type="text/css" media="screen" href="css.php?compress" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment