Skip to content

Instantly share code, notes, and snippets.

@angeliquejw
Last active December 18, 2015 04:59
Show Gist options
  • Save angeliquejw/5729602 to your computer and use it in GitHub Desktop.
Save angeliquejw/5729602 to your computer and use it in GitHub Desktop.
Random background color from specified color array, plus ability to coordinate site elements to match. Based on code from the following: http://www.thecodepress.info/2013/05/change-background-color-on-every.html#.UbHqwpwYh3B http://lab.clearpixel.com.au/2008/06/darken-or-lighten-colours-dynamically-using-php/
<?php
$colors = Array("#028cd5", "#b6cd3f", "#fa6128", "#fdb93c", "#ab4785");
$color_change = "";
$change = rand(1, 5);
switch($change){
case 1: $color_change = $colors[0];
break;
case 2: $color_change = $colors[1];
break;
case 3: $color_change = $colors[2];
break;
case 4: $color_change = $colors[3];
break;
case 5: $color_change = $colors[4];
break;
default: echo "Something going wrong!";
}
function colorBrightness($hex, $percent) {
$hex = str_replace('#','',$hex);
/// HEX TO RGB
$rgb = array(hexdec(substr($hex,0,2)), hexdec(substr($hex,2,2)), hexdec(substr($hex,4,2)));
//// CALCULATE
for ($i=0; $i<3; $i++) {
// See if brighter or darker
if ($percent > 0) {
// Lighter
$rgb[$i] = round($rgb[$i] * $percent) + round(255 * (1-$percent));
} else {
// Darker
$positivePercent = $percent - ($percent*2);
$rgb[$i] = round($rgb[$i] * $positivePercent) + round(0 * (1-$positivePercent));
}
// In case rounding up causes us to go to 256
if ($rgb[$i] > 255) {
$rgb[$i] = 255;
}
}
//// RBG to Hex
$hex = '';
for($i=0; $i < 3; $i++) {
// Convert the decimal digit to hex
$hexDigit = dechex($rgb[$i]);
// Add a leading zero if necessary
if(strlen($hexDigit) == 1) {
$hexDigit = "0" . $hexDigit;
}
// Append to the hex string
$hex .= $hexDigit;
}
return '#'.$hex;
}
$brightness = 0.4; // lighter (add minus to make darker)
$color_lighten = colorBrightness($color_change,$brightness);
?>
<style>
body { background-color:<?php echo $color_change; ?>; }
h1, a:hover, a:active { color:<?php echo $color_lighten; ?>; }
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment