1

I want to have a background image fade in from invisible opacity, to 50% opacity, and stay there.

There was a similar question asked here, but I did not follow along at all, seems complicated. Maybe it'll help someone with my similar issue.

I just want to use CSS only if possible, no JS. This is what I have so far in my style.css:

body {
    background-image: url("img/me.png");
    background-color: #cccccc;
    background-repeat: no-repeat;
    background-position: top;
    background-attachment: fixed;
    animation: fadeInBG 5s; 
}

@keyframes fadeInBG {
    0% { opacity: 0.0; }
    100% { opacity: 0.5; }
}

You will want to change the image url to something else for your testing. Right now, it's applying the animation to the entire page body (including any text on the page), and not touching the background at all, background is always 100% with no animation. The simple text I have in my html file just says:

<h1> Hello world! </h1>

...which DOES do the animation. How can I direct the animation logic to the background image only? I wish you could designate body.background-image instead of body and it would be solved.

Another thing I noticed is that, once the animation is done, the text "jumps" to 100% opacity, it doesn't stay at 50% like I have it set as above. How to fix that?

wildcat89
  • 1,159
  • 16
  • 47

1 Answers1

1

Just add the code below in your CSS code.

body {
    animation-fill-mode: forwards;
}

Useful link: https://developer.mozilla.org/en-US/docs/Web/CSS/animation-fill-mode

Also, I suggest you add a div to achieve it.

.bg-img {
    background-image: url("https://media.istockphoto.com/photos/ginger-cat-portrait-picture-id1290233518?b=1&k=20&m=1290233518&s=170667a&w=0&h=C-eVqPpxcxCFqJsykl4rTzq0Kl995ZHCaLB9BgSgEzk=");
    background-color: #cccccc;
    background-repeat: no-repeat;
    background-position: top;
    background-attachment: fixed;
    animation: fadeInBG 5s;
    /* add */
    animation-fill-mode: forwards;
    position: fixed;
    inset: 0;
    z-index: -1;
}

@keyframes fadeInBG {
    0% {
        opacity: 0;
    }
    100% {
        opacity: 0.5;
    }
}
<h1> Hello world! </h1>
<div class="bg-img"></div>
codewithhong
  • 196
  • 1
  • 7