Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random background images CSS3

I am doing small website, however I have like 5-6 images for my background, and I want to make it random every time I refresh the page. This is what I got in style.css :

html {   
    background:  url(image/l2.jpg) no-repeat center center fixed
    -webkit-background-size: cover
    -moz-background-size: cover
    -o-background-size: cover
    background-size: cover   
}
like image 687
user2136883 Avatar asked Mar 05 '13 18:03

user2136883


People also ask

Can you have two background images in CSS?

CSS allows you to add multiple background images for an element, through the background-image property. The different background images are separated by commas, and the images are stacked on top of each other, where the first image is closest to the viewer.


1 Answers

I would use JS. Take a look at this example:

<html>
<head>
<script type="text/javascript"> 
var totalCount = 8;
function ChangeIt() 
{
var num = Math.ceil( Math.random() * totalCount );
document.body.background = 'bgimages/'+num+'.jpg';
document.body.style.backgroundRepeat = "repeat";// Background repeat
}
</script>
</head>
<body> 
// Page Design 
</body> 
<script type="text/javascript"> 
ChangeIt();
</script> 
</html>

You would need to name your images the proper numbers through the random count and place them in that images folder.

like image 141
Matthew Camp Avatar answered Nov 12 '22 03:11

Matthew Camp