Sunday, May 5, 2013

Change Background Color on every refresh using PHP and CSS

In the last post you have seen how to change background image of the website using PHP. But what if you want to change the background color of a website?. Let's see how to do it using PHP and CSS.




PHP CODE: PHP code to make background color change on every refresh.

1.   <?php
2.      $colors = Array("#242424", "#7A7A7A", "#EBEBEB", "#292929", "#940000"); //Making colors
         array
3.      $color_change = "0"; //Assigning a variable with no value 
4.      $change = rand(1, 5); //Getting random number 
5.      switch($change){
6.         case 1: $color_change = $colors[0];
7.         break;
8.         case 2: $color_change = $colors[1];
9.         break;
10.       case 3: $color_change = $colors[2];
11.       break;
12.       case 4: $color_change = $colors[3];
13.       break;
14.       case 5: $color_change = $colors[4];
15.       break;
16.       default: echo "Something going wrong!";
17.      }
18.   ?>

We are done with PHP and now we are going to embed PHP in HTML.
CSS CODE: Here, in CSS code we'll be embed PHP code. 


1.   body {
2.      background-color:<?php echo $color_change; ?>;
3.   }

Now stick it all together in HTML document and debug it.

2 comments:

  1. i can't even think about using php and css together...this is an awesome example of working with php and css together.

    ReplyDelete
  2. your blog looks good on android

    ReplyDelete

Your Comment Will Be Visible After Approval, Thanks !