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

"Discrepancy in Alignment of Bootstrap's Dual Column Layout

Currently, I am in the process of designing a straightforward two-column layout. This layout will consist of one prominent image at the top followed by two columns underneath - one for images and the other for text. https://i.sstatic.net/sYphQ.png Howeve ...

Implementing Jquery Ajax Autocomplete Feature in JSP

I am currently exploring a tutorial on jQuery autocomplete using remote data. In my JSP page, I have the following code snippet: (getData.jsp) Department t = new Department (); String query = request.getParameter("q"); List<String> ...

What is the best way to adjust the height and width of a div when it comes into view through scrolling?

How can I automatically and frequently change the size of my div when it is scrolled into view? HTML <div id="contact" class="fadeInBlock"> <div class="map"> <div class="pointer"> <div class="dot"></div& ...

Tips for sending an array of data from the client to req.body in an axios request

I am facing an issue with sending user data collected from the front end via an ajax call to an axios post request in the back end. The parameters I need to pass include arrays of data, but when I check the req.body in the backend using console.log(), I no ...

Design the spans to have equal heights that adjust dynamically based on the content entered

I'm facing a challenge that I've been trying to resolve using just CSS, but I've hit a roadblock. The issue at hand involves aligning multiple spans next to each other and making them equal in height. The height is not fixed and depends on ...

What is the best way to equalize the size of mismatched images in CSS?

My Objective https://i.sstatic.net/KgK0F.png I aim to align images of different sizes and shapes within the same frame using only CSS. The image size should adjust proportionally as the browser window is resized. Current Progress JSFiddle Curr ...

Instructions for adding a class when a li is clicked and replacing the previous class on any other li in Vue 2

Even though I successfully used jQuery within a Vue method to achieve this task, I am still searching for a pure Vue solution. My goal is to remove a class from one list item and then add the same class to the clicked list item. Below is the code snippet w ...

iterating over a nested map within a map in an Angular application

I wrote a Java service that returns an observable map<k, map<k,v>> and I'm currently struggling to iterate through the outer map using foreach loop. [...] .then( (response: Package) => { response.activityMap.forEach((key: s ...

What causes the index to display [object Object] rather than an integer in React?

It has been a long time since I last worked with React, and now I'm facing an issue. Whenever I use console.log to display the index within the map function, my console output looks like this: https://i.stack.imgur.com/VbGmE.png However, the result ...

The ChromeDriver capabilities that have been configured are not maintained once the WebDriver is constructed in Node Selenium

I am currently experimenting with adding the default download path using Chrome capabilities in my code snippet below: const test = async () => { let builder = await new Builder().forBrowser("chrome"); let chromeCapabilities = builder.getC ...

Implementing a method in MVC using .NET Core

As a newcomer to MVC, I am facing a challenge with my app. It features a list of links to websites, and I want to increment the "usage" integer each time a link is clicked. public class Link { public int ID { get; set; } [Required] ...

Working with AngularJS: Accessing a JSON file from the local directory

The answers to my previous questions on this topic have not been satisfactory. It seems that most examples and tutorials for AngularJS online always define tiny JSON arrays directly inside the JavaScript code... So, let's simplify things with a basi ...

Using JAVA to generate SVG images, then embedding them into HTML using Base64 encoding URI

I am currently developing a service to generate SVG images. The main criteria is that the generated SVG must be compatible with an img tag (with the added bonus of working in a script tag) and it needs to function without the use of JavaScript. After some ...

Executing a keystroke in Selenium Webdriver using JavaScript

I've been writing a test using Selenium WebDriverJS, and now I need to simulate pressing a key on the keyboard. Is it possible to do this with Selenium WebDriverJS? If so, how can it be done? In Java, we achieve this as follows: driver.findElement(Lo ...

Adjust the div height to 100% in Bootstrap to center text, even with the presence of a navbar

I'm currently using Bootstrap 5 and facing an issue with getting text centered vertically on the page. I attempted to make the container of the div take up 100% of the page by using h-100, but it resulted in overflow due to the navbar occupying some s ...

Creating an ongoing loop endlessly using recursion in node.js

Seeking assistance in creating a recursive loop to continuously iterate through functions in Node.js for flow control. I have tried online tutorials but still struggling to comprehend it fully. Can anyone provide guidance or point me towards a proper tutor ...

Tips on organizing a JSON object for a JavaScript project

For my project, I am designing a data structure that utilizes JSON. My goal is to create an efficient method for searching and editing the JSON object. Which structure would be considered standard in this scenario? Is there a preferred way to implement eit ...

Unlocking the Power of Localization: An Easy Guide to Accessing JavaScript Values

After utilizing the localization helper created by Matt Hawley, I found it to be incredibly effective. However, I am encountering an issue when attempting to retrieve the values in javascript/jQuery. For example, I am unable to fetch the resource text usi ...

Issues with POST server-side JSON output in jQuery DataTables

Attempting to configure my datatable to receive a POST JSON response from the server. Below is the code on the client side: <script> $(document).ready(function() { $('#example').dataTable( { "bProcessing": true, "bServ ...

I am currently using React to implement a feature that displays random facts for 5-second intervals. Despite no errors being displayed, the facts are not appearing on the page as expected

Client side My react application includes a section that is supposed to display random facts at 5-second intervals. Although no errors are displayed, the facts do not appear on the page when I run the code. import React from "react"; import &quo ...