How about mixing up your backgrounds with an overlay effect for a unique look?

Hey there, I'm currently working on adding random backgrounds to my website through an overlay, but I've hit a roadblock when it comes to displaying them.

Here is the code I'm working with:

.css / .php

#intro {
    background:
              /* top, transparent black gradient */ 
          linear-gradient(
          rgba(0, 0, 0, 0.7), 
          rgba(0, 0, 0, 0.7)
         
       ),
      url(/images/<?php echo $selectedBg; ?>);
      background-size: 100% auto, cover;
      background-attachment: fixed, fixed;
      background-position: top left, bottom center;
      background-repeat: repeat, no-repeat;
         width: 100%;
         height: auto;
  
  
  }
<?php
      $bg = array('bg-01.png', 'bg-02.jpg' ); // array of filenames
  
      $i = rand(0, count($bg)-1); // generate random number size of the array
      $selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
    ?>

I have double-checked the file names for bg-01.png and bg-02.jpg and they seem correct. Any help or guidance on what I might be doing wrong would be greatly appreciated.

Answer №1

Combine your Css and php code within the same file and make sure to load the php code before the css.

<?php
      $bg = array('bg-01.png', 'bg-02.jpg' ); // array of filenames

      $i = rand(0, count($bg)-1); // generate random number size of the array
      $selectedBg = "$bg[$i]"; // set variable equal to which random filename was  chosen
?>

<style> 
     #intro {
        background:
          /* top, transparent black gradient */ 
      linear-gradient(
      rgba(0, 0, 0, 0.7), 
      rgba(0, 0, 0, 0.7)

 ),
 /* bottom, image */

        url(/images/<?php echo $selectedBg; ?>);
        background-size: 100% auto, cover;
        background-attachment: fixed, fixed;
        background-position: top left, bottom center;
        background-repeat: repeat, no-repeat;
        width: 100%;
        height: auto;


    }

 </style>

Answer №2

Why even consider using PHP in this scenario? It's messy to mix CSS and PHP together like that.

The cleaner solution would be to use JavaScript instead.

<script type="text/javascript">
$(document).ready(function() {
    var backgroundList = ['bg-01.png', 'bg-02.png'];
    var randomBackground = backgroundList[Math.floor(Math.random() * backgroundList.length)];

    $('#intro').css('background', randomBackground);

    var imagePath = '/images/';
    $('#intro').css('background', imagePath + randomBackground);
}); 
</script>  

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Eliminating empty elements from arrays that are nested inside other arrays

I am facing a challenge with the array structure below: const obj = [ { "description": "PCS ", "children": [ null, { "name": "Son", ...

Utilizing the `filterBy` function with a custom select list that changes dynamically

I'm currently in the process of constructing a form with an extensive selection of drop-down items utilizing vue.js. My approach involves implementing the dynamic select list as detailed in this documentation: However, I am interested in providing us ...

Send form information using AJAX response

I have successfully implemented a feature where I load an iframe into a div with the id of #output using AJAX. This allows me to play videos on my website. jQuery( document ).ready( function( $ ) { $( '.play_next' ).on('click', fun ...

After logging in, I am unable to redirect to another PHP page as the login form simply reloads on the same page

Lately, I've encountered an issue that has persisted for a few days. The login validation is functioning flawlessly. However, the problem arises when attempting to redirect to another page, specifically 'index.php', after logging in. Instead ...

`Resizing Images with Cropping Functionality`

I am looking to develop a feature that enables users to resize images after uploading them. The image should be placed within a crop frame, allowing users to drag, move, and resize it as needed. Here is a visual concept of what I have in mind. If anyone c ...

What is the best way to eliminate specific elements from an array of objects in MongoDB aggregate based on a condition?

I have a database of documents called ChatRooms stored in MongoDB with the following structure: { _id: ObjectId('4654'), messages: [ { user: ObjectId('1234'), sentAt: ISODate('2022-03-01T00:00:00.000Z') ...

Is there a way to prevent the window.status from appearing?

I currently have the following code snippet: <a class="button accessLink" id="loginLink" href="#" data-action="Login" data-dialog="access" data-disabled="false" data-entity="n/a" ...

Guide to Changing the Value of a Textbox Using Form jQuery

For instance: <form id="example1"> <input type="text" name="example_input"> </form> <form id="example2"> <input type="text" name="example_input"> </form> In the code above, both text boxes have the same name. H ...

The functionality of socket.io is not functioning properly on the server, resulting in a 404

I encountered errors while working on a simple socket.io project on my server. The IP address I am using is . All files are stored in public_html and can be accessed through the URL: . Here are the code snippets: <!doctype html> <html> < ...

Retrieving localStorage data from another webpage

I recently created an account and I hope my question is clear. I have two separate pages on my website - one for a menu and the other for an HTML game. The menu has two buttons, one to start a new game and the other to continue from where you left off. How ...

Discrepancies in Video Element Size: Mobile Versus Desktop

Why does the video element have different sizing behavior between mobile and desktop? I noticed on this website that on desktop Chrome, its width is about 35% of the browser while on iPad Chrome it's only about 10% Does anyone know why this is happen ...

Generating unique identifiers for ng-model in AngularJS

Issue - ng-model is not generating dynamically. I have dynamic input boxes and I am attempting to create ng-model dynamically like test[1], test[2], etc. However, when inspecting the form with Firebug, all input elements only show - test[shiftnumber]. HT ...

Creating multiple unique custom attributes for a specialized HTML element

Creating getter/setter methods for a custom attribute on a custom HTML element is quite simple: customElements.define('custom-el', class extends HTMLElement { static get observedAttributes() { return ['customAttr'] ...

Incorporating the click function into dynamically created divs using jQuery

When I receive an array from AJAX, I am dynamically creating Divs based on the number of items in the array. Each div has a unique Id and I want to attach a Click event to all of them. The goal is for the user to click on one of the generated divs to tri ...

Implementing alphabetical pagination in PHP

I am trying to implement alphabetical pagination in php, but I am facing a problem. When I click on any alphabet, the selected alphabet shows up in the address bar, however, the data starting from the selected alphabet is not displayed. Here are my databa ...

What is the reason behind the Typescript compiler not converting .ts files to .js files automatically?

Displayed below are the folders on the left showcasing my Typescript file in /src (blue) compiled into Javascript in /dist (purple) using tsc. https://i.stack.imgur.com/7XNkU.png In the source file on the left, there is a reference to a .ts module file t ...

Is it more beneficial to categorize REST-based modules/controllers by resource or by specific action/feature?

I'm facing a scenario that goes like this: Endpoint 1: Retrieve all books in the United States owned by John with a GET Request to /country/us/person/john/books Endpoint 2: Get all books owned by John in every country with a GET Request to /person/j ...

Enhancing the alignment of div elements

Our objective is to have two divs aligned next to each other. Here is the HTML code: <div class="test1>Text 1</div> <div class="test2>Text 2</div> And here is the CSS code: .test1 { float: left; } .test2 { float: left; } ...

Transforming "datetime-local" into java.sql.Timestamp

I am working on a JSP page that has a form containing an input field with type "datetime-local". The data from this form is then passed to a servlet using the following code: String resetTimeString = request.getParameter(RequestParameterName.RESET_TIME); ...

What is the best way to horizontally align a group of list elements while also displaying them side by side?

I've been working on creating a Sign Up page and here is the code I have so far: <div class="form"> <ul class="tab-group"> <li class="tabsignup"><a href="/signup.html">Sign Up</a ...