Implementing two background images and dynamically adjusting their transparency

With the challenge of loading two fixed body background-images, both set to cover, I encountered a dilemma. The text on the page was extending below and scrolling, along with top and bottom navigation icons. As expected, the second background covered the first, giving the appearance of a single loaded background.

In seeking guidance from previous inquiries, I utilized body {} for the first (now concealed) background-image and body:after {} for the second (visible, adjustable opacity) background-image.

By applying CSS body:after {opacity:.5} or any value between 0 and 1, I managed to achieve a specific effect with the top background while maintaining full opacity for text and navigation icons. Yet, altering the opacity value proved to be a challenge. Once equipped with expert assistance, I aimed to incrementally adjust opacity values from 1 to 0 in order to fade out the top background using a timed sequence with 11 frames at suitable intervals.

Below are the successful code snippets as well as my unsuccessful Javascript endeavor to access the opacity value.

(P.S.: thanks to @RickardElimää's exceptional ultimate answer, the top background initially appears transparent and eventually transitions into a fade-in effect.)


body {
  background-image: url('./MyPhoto-1.jpg') ; 
  position: static; /* necessary for Edge 10 compatibility */
  /* z-index: -2 ; */
  background-position: center center ; 
  background-repeat: no-repeat ; 
  background-attachment: fixed ; 
  background-size: cover ; 
}

body:after { 
  content: " ";
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-image: url('./MyPhoto-2.jpg') ; 
  position: fixed ; 
  z-index: -2 ; 
  background-position: center center ; 
  background-repet: no-repeat ;
  background-attachment: fixed ; 
  background-size: cover ; 
  opacity: 0.4 ; /* set arbitrarily and requiring Javascript access */
}

<script>//Issue encountered when trying to access opacity value through scripting
  // document.body.getElementById("triedDivAndBodyTag").style.opacity = ".8"
  document.getElementByID("body:after").style.opacity="0.8";
</script>

Answer №1

If you're looking to enhance your website's design, consider utilizing CSS variables. They provide a convenient way to manage and apply styles across your site. Additionally, incorporating CSS animations can improve performance and create a more visually appealing user experience.

:root {
  --background-opacity: 0.4;
}

body {
  background-image: url('./MyPhoto-1.jpg') ; 
  position: static; /* use this for compatibility with Edge 10 */
  /* z-index: -2 ; */
  background-position: center center ; 
  background-repeat: no-repeat ; 
  background-attachment: fixed ; 
  background-size: cover ; 
}

body:after { 
  content: " ";
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-image: url('./MyPhoto-2.jpg') ; 
  position: fixed ; 
  z-index: -2 ; 
  background-position: center center ; 
  background-repeat: no-repeat ; 
  background-attachment: fixed ; 
  background-size: cover ; 
  opacity: var(--background-opacity);
  transition: opacity 1100ms;
}

<script>
  document.documentElement.style.setProperty('--background-opacity', 0.8);
</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

HTML display issue: Angular curly braces failing to show up

I am facing a peculiar issue in my browser where the content inside the angular curly braces is not being displayed. Even though there are no errors in the console and the value gets logged successfully, the page appears blank. The expected output should b ...

Showing how an iframe can adjust its height to 100% within a div element

Currently, I have a player status script implemented on our Minecraft Server. This script displays the server name, IP address, and the heads of the players currently online. The setup includes two div boxes for the status box: one outer box to fix its pos ...

AngularJS text area not displaying HTML content

In my Ionic's App, I have a textarea that is used for creating or editing messages. However, I am encountering an issue where the textarea does not render HTML tags when trying to edit a message. I attempted solutions such as setting ng-bind-html and ...

Issue with AngularJS Cross-Origin Resource Sharing (CORS) when making HTTP requests, whereas standard Ajax and jQuery are

I'm currently dealing with a straightforward cross-domain service that is set up to handle Simple CORS requests. When I try to access it using a plain xmlHTTP call or jQuery($.ajax), everything works smoothly. However, when attempting to make the call ...

Are you interested in using jQuery and/or AJAX to retrieve the latest images from a website?

I had to utilize a Wikipedia API in order to retrieve images from the New Jersey website, and I devised two methods to carry out similar tasks. The initial approach involved using JSON, but it ended up pulling the entire page content. <script type="tex ...

What are the consequences of altering meta tags once the DOM has fully loaded?

While delving into the A-Frame source code, I noticed that the library uses JavaScript to set various meta tags. It seems safe in the context of A-Frame as Mozilla recommends importing their library as a blocking, synchronously loaded script in the <he ...

Transferring Information Across Javascript Documents

I am facing a dilemma with using JSON data generated by one script in another script. I am unsure where to begin and have considered saving the JSON string to a text file for the second script to use, but this feels like a workaround rather than a proper s ...

Ways to retrieve information from a POST request

I am looking for assistance on extracting data from a post request and transferring it to Google Sheets while also confirming with the client. Any guidance or support would be highly appreciated. Thank you. My project involves creating a web application f ...

The scrolling feature induces a contraction to the left side

Recently, I implemented the code below to fix my menu when scrolling the page: var num = 5; $(window).bind('scroll', function () { if ($(window).scrollTop() > num) { $('.scroll').css({'position':'fixed&apo ...

Determine the specific cell involved in an HTML5 drag-and-drop interaction within a table

I've been experimenting with the HTML5 drag and drop functionality in an Angular project. Here's the setup I'm working with: A container containing draggable 'objects' A table where users can drop the dragged elements Following ...

Double execution of the Angular customFilter function

My goal is to use a custom filter in Angular to filter an array. Essentially, I have a binding set up like this: {{ myData.winners | getWinnerString }}, which returns an array of items with a length ranging from 1 to 4. If the array consists of more than ...

collapse each <b-collapse> when a button is clicked (initially shown)

I am facing an issue with a series of connected b-buttons and b-collapse, all initially set to be visible (open). My goal is to hide them all when a toggle from my parent.vue component is activated - so upon clicking a button in the parent component, I wa ...

Intercepting and handling errors thrown by a Node module

I have been encountering an issue with a module that throws errors without them being returned as part of the callback, causing the program to stop when an error is thrown. The code snippet I am using looks like this: co(function*(){ try{ for (let ...

Sharing data between AngularJS and D3 with JSON - a guide

When working on my application controller, I typically send a request to my API. This is what it usually looks like: .state('state1', { url: '/datas/:id', templateUrl: 'myurl.com', title: 'title', ...

Exclude the key-value pair for any objects where the value is null

Is there a way to omit one key-value pair if the value is null in the TypeScript code snippet below, which creates a new record in the Firestore database? firestore.doc(`users/${user.uid}`).set({ email: user.email, name: user.displayName, phone: ...

Do you need to redeclare the type when using an interface with useState in React?

Take a look at this snippet: IAppStateProps.ts: import {INoteProps} from "./INoteProps"; export interface IAppStateProps { notesData: INoteProps[]; } and then implement it here: useAppState.ts: import {INoteProps} from "./interfaces/INo ...

Align two lines of text in the center of a table

I need assistance with creating a table in HTML for an email. I would like to display a two-lined text, where the top line is formatted in bold. <table style="width:100%"><tr > <td style="background-color:#000000;color:#fff;font-fam ...

Console displaying a 400 bad request error for an HTTP PUT request

I'm currently in the process of developing a react CRUD application using Strapi as the REST API. Everything is working smoothly with the GET, DELETE, and CREATE requests, but I encounter a 400 bad request error when attempting to make a PUT request. ...

Basic draggable pop-up window using HTML5 for a seamless experience

Can anyone provide me with helpful resources or tutorials to create a draggable popup using HTML5 without jQuery? I want to keep it simple and avoid external libraries like jQuery UI. Currently, I have an absolutely positioned div that looks like a popup ...

template not being loaded with form

My Django form is not showing up when I try to implement it. Even after checking the browser's inspector, there is no sign of it being loaded at all. If more information is required, please let me know. Here is the project structure: /beerad url ...