Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS animate transition of background image getting darker

So I'm building a page that has a background image:

body {
    background:url(images/bg.png) center center no-repeat fixed;
    -webkit-background-size:cover;
    -moz-background-size:cover;
    -o-background-size:cover;
    background-size:cover
}

The page loads with a div that looks like a alert/message. When this div loads I want a short animation of the background-image getting darker,
Right now I use this:

back { 
    background:rgba(0,0,0,.95);
    display:block;
    height:100%;
    left:0;
    opacity:1;
    position:fixed;
    top:0;
    width:100%
}

This makes it darker, but I want this to happen gradually in a smooth transition/animation.

like image 864
Batou069 Avatar asked Mar 17 '23 13:03

Batou069


1 Answers

You can use @keyframes for this. I don't know what your HTML looks like, but here's a little demo:

.back { 
    background:rgba(0,0,0,.95);
    display:block;
    height:500px;
    left:0;
    opacity:1;
    position:fixed;
    top:0;
    width:500px;
}

@keyframes back-change {
   from { background: rgba(133,133,133,.95) }
     to { background: rgba(0,0,0,.95) }
}

.back {
  animation: back-change 4s linear;
}
<div class="back"></div>

I set it to change from light to dark over 4s in a linear pattern. You can change the duration or change the pattern to whatever you want (none, infinite, etc.).

Notice that the name back-change that follows the @keyframes word is what you'll have to call in the the animation property later on. If you change the name in one spot, you'll have to change it in both.

Here's a JSFiddle Example as well for messing around with on your own.


You can also use CSS3 Transitions as well. These have been supported a little longer in web browsers.

.back { 
    background:rgba(0,0,0,.95);
    display:block;
    height:500px;
    left:0;
    opacity:1;
    position:fixed;
    top:0;
    width:500px;
    transition-property: background-color;
    transition-duration: 0.3s;
}

.back:hover {
    background-color: rgba(133,133,133,.95);
}
<div class="back"></div>

Again, here's a JSFiddle Example for you to play with.

like image 132
TylerH Avatar answered Apr 06 '23 17:04

TylerH