search

Home  >  Q&A  >  body text

Add animation to the background-image property in the body tag: step-by-step guide

I am using background image in style tag.

<style>
body {
 background-image: url("img.jpg");
 background-size: cover;
 transition: background-image 4s linear;
 }
</style>

I want the image to fade in without adding a separate div to the page. Can this goal be achieved?

P粉347804896P粉347804896243 days ago442

reply all(2)I'll reply

  • P粉940538947

    P粉9405389472024-03-30 19:07:40

    Yes, it is possible. You can do this.

    @keyframes mymove {
         from {
          /* background: white; */     
         }
         to {
          background: url("https://www.shutterstock.com/image-photo/welded-metal-chain-various-rigging-260nw-2238426561.jpg");
           }
    }
    body {        
            animation: mymove 2s infinite;
          }
    
    
    
    

    reply
    0
  • P粉541551230

    P粉5415512302024-03-30 13:40:37

    This is a CSS-only approach. However, there is a caveat, CSS cannot wait for events, so it has no way of knowing when the entire site has loaded.

    Instead, in this snippet, it waits 1 second before starting to introduce the background image that is located on the body's before pseudo-element.

    body {
      width: 100vw;
      height: 100vh;
      /*just for demo */
      position: relative;
    }
    
    body::before {
      background-image: url(https://picsum.photos/id/1015/1024/768);
      background-size: cover;
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: -1;
      opacity: 0;
      animation: fadein 5s 1 1s linear forwards;
    }
    
    @keyframes fadein {
      to {
        opacity: 1;
      }
    }
    Hello, this is some text in the body. It will be seen even before the background starts to fade in.

    reply
    0
  • Cancelreply