A client asked me to implement function that allows to change background image randomly after each refresh. After some time of messing with rotation scripts I decided to create something myself. Here is my solution.
The first we have to prepare CSS. We will use an image with fixed position and 100% width and height.
html,
body { height: 100%; }
img#bg {
position:fixed;
top:0;
left:0;
width:100%;
height:100%;
}
And this code implements image into the HTML code. Put the code right after
<body>
<?php $random_image = rand(1, 5); /*let's choose random image...*/ ?>
<img id="bg" alt="" src="<?php bloginfo('stylesheet_directory');?>/images/<?php echo $random_image; ?>.jpg" />
Do not forget to name images you want to use for background like 1.jpg, 2.jpg, 3.jpg etc.
Hi there, how would you code the CSS such that the random image is tiled accross the background?
Thanks!
Where do you change the name of the images?? here?
rand(1, 5)
as in
rand(/imgs/243.jpg, /imgs/285.jpg)
Is that right? If so, this doesn’t work for me.
I’m using WordPress, dropped this in the stylesheet:
img#bg {
position:fixed;
top:0;
left:0;
width:100%;
height:100%;}
and I dropped the other code behind
<body >
as
<img id="bg" alt="" src="/images/.jpg” />
oops…forgot code snippet wrapper.
<body <?php body_class(); ?>> <?php $random_image = rand(/imgs/243.jpg, /imgs/285.jpg); /*let's choose random image...*/ ?> <img id="bg" alt="" src="<?php bloginfo('stylesheet_directory');?>/images/<?php echo $random_image; ?>.jpg" />