How can I make my background image fade in with the same transition as the rest of my webpage using CSS and HTML?

108 Views Asked by At

I have next code to make a fade transition but my background image load first and without fading?

   body {
    opacity: 0;
    transition: opacity 5s;
   }

and then:

   <body onload="document.body.style.opacity='1'">

And the background image loads first than rest.

I expect the background image loads with the same fading time than te rest.

2

There are 2 best solutions below

2
Offeyicial On

document.addEventListener('DOMContentLoaded', function() {
  document.body.classList.add('loaded');
});
body {
  opacity: 0;
  transition: opacity 5s;
}

.background-image {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('path/to/your-image.jpg');
  background-size: cover;
  background-position: center;
  opacity: 0;
  transition: opacity 5s;
}

body.loaded {
  opacity: 1;
}

body.loaded .background-image {
  opacity: 1;
}
<body>
  <div class="background-image"></div>
  <!-- Rest of your webpage content -->
</body>

0
zer00ne On

Leave <body> as normal (no opacity property is necessary). Define @keyframes for the different opacity values. Add a position: fixed/z-index: 1 to a direct descendant element of <body> (in the example below, it's a <section>). Assign animation property to said element.

Details are commented in example

/**
 * Define a simple set of keyframes named "fade"
 * from {a state of visible} to {a hidden state}
 */
@keyframes fade {
  from {
    opacity: 1.0;
  }
  to {
    opacity: 0.0;
  }
}

body {
  min-height: 100vh;
  margin: 0 /* Allows it to be covered edge to edge. */;
  background: url(https://i.ibb.co/pKPKR1v/wall0.jpg) no-repeat center; 
  background-size: cover;
}

section {
  position: fixed /* Place fixed within the viewport. */;
  z-index: 1 /* Place "over" <body>. */;
  width: 100vw;
  height: 100vh;
  background: black;
  /**
   * Reference @keyframes "fade"
   * Duration lasts for 5 seconds
   * Forwards fill-mode ensures that animation stays at the
   * last keyframe.
   */
  animation: fade 5s forwards;
}
<section></section>