skip to Main Content

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

Answers


  1. 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>
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search