Load random image in background-image using css

Asked

Viewed 415 times

0

It is possible using css only, load random images into the background-image property of any element?

For example I have a Section

<section id="slide">

</section>

And I have a folder called img that contains 5 files

background-1-img.png
background-2-img.png
background-3-img.png
background-4-img.png
background-5-img.png

Every time the page containing this Section was loaded, one of the images in this directory should be set in the background-image property of the Section way random.

My question is, can I do this only with CSS, or will I need Javascript for this?

  • 2

    I believe that only in css this randomness will not be possible, you have the knowledge to solve this in js or other language of your choice?

  • Yes, in js I have, but I was wondering if I could do in css

  • The closest you get to getting what you want is using animation. It’s not random, but it allows images to change. If you want an example to work with, just contact me. If you want the random part you must always use JS.

  • I’m pretty sure that only with CSS This is not possible, perhaps with PHP, making a random query in the database (Mysql). The query would look something like this: "SELECT * FROM banners ORDER BY RAND() LIMIT 1", With this you save in a variable.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.