0

I want to set a random background color on a css-class... I already got this PHP-Code:

<?php $color = sprintf(“#%06x”,rand(0,16777215)); ?> 

This is my style.php:

<?php
    header('Content-Type: text/css');

?>

body {
    background: INSERT PHP COLOR HERE - BUT HOW?;
}
9
  • 1
    body {background-color: <?php echo $color; ?>;} Exactly the same as if you needed to insert it into HTML. Commented Nov 23, 2012 at 13:58
  • 1
    Hopefully your real code doesn't have those slanty quotes in the sprintf() “#%06x”. You need real double quotes for PHP code. "#%06x" Commented Nov 23, 2012 at 14:00
  • @MichaelBerkowski which is, I guess, a pretty bad idea by itself :-) Commented Nov 23, 2012 at 14:02
  • @MichaelBerkowski Then I didn't say anything :P Commented Nov 23, 2012 at 14:03
  • @JanDvorak I don't think so, it's pretty common actually. CSS itself has no way of propagating a variable through so you can't easily change a color across a whole set of css. Useful for variable themeing, stuff like that. Commented Nov 23, 2012 at 14:03

5 Answers 5

5

is this what you want:

body {
    background: <?php echo $color; ?>;
}

the complete line would be:

<?php
$color = sprintf("#%06x",rand(0,16777215));
header('Content-Type: text/css');
?>
body {
    background: <?php echo $color; ?>;
}
Sign up to request clarification or add additional context in comments.

Comments

1

and where is your question? just kidding.

insert the variable directly in the mentioned css line.

body {
  background: <?php echo $color?>;
}

to get it working ;)

Comments

0

Why not make a array with colors to pick random color from?

<?php
$input = array("#000080", "#00CED1", "#191970");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>

Just replace the names with hex codes.

http://php.net/manual/en/function.array-rand.php

Comments

0

Change your file like this.

<?php
    header('Content-Type: text/css');
    $color = sprintf(“#%06x”,rand(0,16777215));
?>

body {
    background: <?php echo  $color; ?>;
}

Comments

0
<?=$color; ?>  

The body is inside the PHP document?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.