-->

Pages

Tuesday 14 March 2017

Randomizing Background Images using PHP and CSS !

This is a cool trick to present every time a new background image to the user, most of the time the user gets bored of seeing the same background-image all the time, so In order to make it engaging the designer and the developer team come up with this approach of randomizing the background images, and everytime present a new image when the page is refreshed or reloaded.



In this article of mine, I am presenting a very simple and minimal approach for achieving this cool trick, here I am using PHP and along with it, I am using simple CSS, to assign the background to the <body> of my HTML document.



Here is the code snippet:


<?php


  $bg = array('bg-01.jpg', 'bg-02.jpg', 'bg-03.jpg', 'bg-04.jpg', 'bg-05.jpg', 'bg-06.jpg', 'bg-07.jpg','bg-08.jpg','bg-09.jpg','bg-10.jpg','bg-11.jpg' ); // creating an array of filenames


  $i = rand(0, count($bg)-1); // generating a random number according to the size of the   array

  $selectedBg = "$bg[$i]"; // here we are setting the variable equal to which random filename that has occured
?>
<html>
    
    <head><title>Random Background</title>
        <style type="text/css">


body{

background: url(images/<?php echo $selectedBg; ?>) no-repeat;
background-size: cover;
}


</style>

    </head>
    <body>
        
   </body>

</html>

Points to Remember:
  • Here I have added all the images inside a folder called "images", therefore I am giving the path like (images/<?php echo $selectedBg; ?>).

  • no-repeat background property is used to not repeat the image either horizontally or vertically.

  • background-size: cover is used to cover the entire area where the content is residing with the background image.


This is a very simple and awesome trick to change the background image on page refresh, make sure to implement this if you feel like so and if you guys have any doubt regarding this trick, feel free to ask me.

No comments:

Post a Comment

Thanks for Your Time!