Alternative image to be used as background if the default image is not available

I am looking to designate an image as a background, but the image file may be named either bg.png or bg.jpg.

Is there a way without using JavaScript to set up a fallback option for an alternate image if the default background image is not available?

body{
    background: url(bg.png);
    background-size: 100% 100%;
    width: 100vw;
    height: 100vh;
    margin: 0;
}

Answer №1

To utilize multiple backgrounds without transparency and covering all available space or having the same size, you can use the following CSS code:

div{
     background-image: url('http://placehold.it/1000x1000'), url('http://placehold.it/500x500');
     background-repeat:no-repeat;
     background-size: 100%;
     height:200px;
     width:200px;
}
<div></div>

If the first image is not available, the second one will be displayed instead.

div{
     background-image: url('http://placehol/1000x1000'), url('http://placehold.it/500x500');
     background-repeat:no-repeat;
     background-size: 100%;
     height:200px;
     width:200px;
}
<div></div>

Answer №2

If you want to specify multiple backgrounds, you can achieve this by:

  background-color: green;
  background-image: url('bg.png'), url('bg.jpg');

This code will first attempt to set the background to bg.png. If this image is not found, it will then default to using bg.jpg. In the rare case that neither image exists, the background color will fallback to a solid shade of green.

Do keep in mind that the order in which images are listed matters. The browser will display the first specified image on top of any subsequent ones. Furthermore, if the png image includes transparency, both images will partially show through.

For a live demonstration, check out this demo link. Feel free to test the code by purposely breaking either image URL.

Answer №3

Even though this approach incorporates JS, it fetches the initial image utilizing CSS, and will exclusively resort to JS for retrieving the alternative image if the primary image fails to load.

To begin, define the main image using CSS in the usual manner, like so:

.myImage {
    background-image = "main-image.png";
}

Then, include the following JS code that kicks in only when the main image fails to load (otherwise, the fallback image won't be fetched).

var img = document.createElement("img");
img.onerror = function() {
    var style = document.createElement('style');
    style.innerHTML = '.myImage { background-image = url("http://fallback_image.png"); }';
    document.head.appendChild(style);
}
img.src = "main_image.png";

Keep in mind that you can insert multiple rules into the CSS block appended through javascript, such as in cases where this needs to be done for multiple elements.

Answer №4

To achieve a background image using CSS, you can utilize the same image URL in a hidden image tag. In case of an error, you can modify the image URL and display it.

<div
  style={{ backgroundImage: `url(${imageSrc})` }}
>
  <img
    style={{ display: "none" }}
    src={imageSrc}
    onError={(e) => {
      e.currentTarget.src = brokenImageFallbackUrl;
      e.currentTarget.style.display = "block";
      // Alternatively, keep this image hidden and set the background image of the parent div
    }}
  />
</div>

Answer №5

I needed a solution that prevents loading images twice, as using a CDN with fallback was not effective if it always loaded original images as well. This led me to create a JavaScript script to manipulate the loaded CSS DOM.

var cdn = "https://mycdn.net/"; // Original location or item to locate
var localImageToCssPath = "../"; // Replacement, CSS files are in /css/ directory.

function replaceStyleRule(allRules){
  var rulesCount = allRules.length;

  for (var i=0; i < rulesCount; i++) 
  {
    if(allRules[i].style !== undefined && allRules[i].style !== null &&
        allRules[i].style.backgroundImage !== undefined &&
        allRules[i].style.backgroundImage !== null &&
        allRules[i].style.backgroundImage !== "" &&
        allRules[i].style.backgroundImage !== "none" &&
        allRules[i].style.backgroundImage.indexOf(cdn) > -1
            )
      {
        var tmp = allRules[i].style.backgroundImage.replace(cdn, localImageToCssPath);
        //console.log(tmp);
        allRules[i].style.backgroundImage = tmp;
      }
      if(allRules[i].cssRules !== undefined && allRules[i].cssRules !== null){
        replaceStyleRule(allRules[i].cssRules);
      }

  }
}
function fixBgImages(){
  var allSheets = document.styleSheets;
  if(allSheets===undefined || allSheets===null){
    return;
  }
  var sheetsCount = allSheets.length;
  for (var j=0; j < sheetsCount; j++) 
  {
    var allRules = null;
    try{
        allRules = allSheets[j].cssRules;
    } catch(e){
        // Access can be denied
    }
    if(allRules!==undefined && allRules!==null){
        replaceStyleRule(allRules);
    }
  }
}

// use fixBgImages() in case of an error

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

Bottom-aligned footer that remains in place instead of sticking to the page

I am attempting to position a footer at the bottom of the page, without it being sticky. Instead, I want it to remain at the bottom in case the user scrolls down there. Although it technically "works," there appears to be some white space below the footer ...

React state update not triggering a component re-render

I've been attempting to toggle the visibility of a div by clicking on another div, but I'm encountering an issue. The div becomes invisible on the first click only if it was visible initially. After that, it remains invisible and does not update. ...

Filtering data in a table using Jquery based on specific columns and headers

To retrieve a price value from an HTML table based on a specific column and header, follow these steps: Here is how the table is structured: https://i.sstatic.net/UM3MA.png The HTML code appears as follows: <input id="search_height" placeholder= ...

Unlocking Secret Data with External JavaScript

Currently, I am focusing on validating user input, specifically the name to ensure it is at least 6 characters long. Although I plan to implement more validation, I am facing an issue with error display. When the JavaScript code is embedded within the HTML ...

How come my jQuery validation needs two clicks to activate?

I am experiencing an issue with a comments form that has 2 fields: Author and Message. Upon clicking the submit button, the validation does not trigger initially. However, if I click the submit button again, then the validation works as expected. Any tho ...

Updating the image source attribute using Vue.js with TypeScript

Let's discuss an issue with the img tag: <img @error="replaceByDefaultImage" :src="urls.photos_base_url_small.jpg'"/> The replaceByDefaultImage function is defined as follows: replaceByDefaultImage(e: HTMLImageElement) ...

Creating a Gradient Effect for Partial Next Slide on Slick Slider using Bootstrap 4

I am currently designing a responsive carousel using Bootstrap-4 and slick.js. With the center-mode enabled, I noticed that it shows a partial next slide. I am interested in adding a gradient to this partial next-slide, but I am uncertain about how to acco ...

Issue with HTML CSS: There is a gap between the words "Get" and "started", causing "get" to appear on

Greetings, it appears I am encountering an issue with my website. When I refer to "Get Started," it displays as "GetStarted." However, when I insert a space between "Get" and "started," it separates onto two lines as "Get" on the first line and "started" o ...

Vue: Implement out-in transition where the incoming element appears before the outgoing element has completely disappeared

Check out my code on Codepen: here In this scenario, I have set up two div elements: Block 1 and Block 2. The functionality I am looking for is when a button is clicked, Block 1 smoothly translates to the left until it goes out of view. Once that happens ...

What are the best ways to utilize dynamic CSS on a smartphone browser for optimal performance?

Struggling to optimize my web application for mobile devices, I've encountered challenges with consistent display across different browsers. My idea is to utilize device capability detection to adjust widths and font sizes dynamically based on screen ...

The page is not loading correctly until a refresh is done

My website seems to be displaying incorrectly on most browsers until the page is refreshed. Check it out here: I'm puzzled as to why this issue is occurring and why it resolves itself upon refresh (even without clearing the cache). The layout consis ...

Exploring Line-height CSS Properties in Different Web Browsers

I'm currently attempting to determine if there is a method to inspect each line element in a browser individually. Currently, when right-clicking on a line of text, it visualizes the entire paragraph. However, I am interested in visualizing each line ...

Message within the boundary of the input field

Click here to view the image It would be great to have the text "text name" displayed on the border of the input box. Here is the HTML code - <input type="text" id="text creator" class="form-control" placeholder="text creator" na ...

Is there a way to retrieve the value from a select tag and pass it as a parameter to a JavaScript function?

I would like to pass parameters to a JavaScript function. The function will then display telephone numbers based on the provided parameters. <select> <option value="name-kate">Kate</option> <option value="name-john">John& ...

"Utilize Rotate3d() to rotate the content of a div element

Looking for a way to make a div fold down from the top in webkit. Currently experimenting with rotate3D, but struggling with the rotation being measured from the center of the div. Does that explanation clarify things? ...

Guide to obtaining the root directory in order to send AJAX requests to a server

I am currently working on a small Node.js project where the client side will be making multiple AJAX requests to the server. I want the code to be able to work with any webpage, but I realized that the path is relative to the page's location. How can ...

The div inside an iframe is not displaying the desired background color as intended from the parent page

The code snippet below is included in the <head> section of the main page: <script type="text/javascript"> $(document).ready(function () { $('#innerframe').load(function () { $(this).contents().find($(".TitleB ...

Positioning parent and child elements using CSS

If you have a moment, please check out this URL where I've provided a more detailed explanation of the issue: How to Make an Image Responsive Within a Division I am looking to adjust the width of .slider-wrapper to 100%. Can anyone advise on how to u ...

Difficulty with NodeJS, Hapi, and Cascading Style Sheets

I've decided to challenge myself by creating a small webhost using Node.js with hapi. Even though I'm not an expert in Node.js, I am eager to learn as much as possible. Currently, my main issue revolves around fetching a CSS file from an include ...

The spacing between images on mobile devices is excessive

My images on mobile have too much space between them: mobile version They appear fine in Dev Tools: dev tools version This is my HTML: <div class="container-fluid"> <!-- <br> --> <div class="row"> ...