0

I'm using css transitions to cause a fade-in and fade-out effect on a background-image property. The property gets changed via jquery when the user scrolls.

It initially did not work on any browser. I found that setting an completley empty/transparent PNG file on the original element made chrome work, but the other browsers still don't.

Here's an example of the code:

nav {
background:url(/img/empty.png);
background-origin:border-box;
background-position:top;
background-repeat:repeat;
background-size:50px 50px;

transition: background 1s ease-in-out;
-moz-transition: background 1s ease-in-out;
-webkit-transition: background 1s ease-in-out;

}
.contrast {
    background:#3a3a3a url(/img/xnav.jpg);
    background-origin:border-box;
    background-position:top;
    background-repeat:repeat;
    background-size:50px 50px;
}

The contrast class gets applied to the nav element via jquery. It only seems to fade out on most browsers, but not fade in. It works properly in chrome.

Q1: Is there a cleaner way to do this? Adding a transparent PNG as a background element to the nav element seems like a hack.

Q2: This still doesn't work on firefox, IE or Safari. Can anyone suggest a clean fix?

George43g
  • 565
  • 10
  • 20
  • CSS transition just calculates the difference between to values of a style (e.g., background, width, ...). But I don't think it is able to calculate the difference between two (background) images... – mrmoment Aug 08 '14 at 01:57
  • This code works in chrome. It fades in/out the background image. – George43g Aug 08 '14 at 02:00
  • OK, so you just want the opacity transition. Maybe you can try http://stackoverflow.com/questions/19808764/transition-for-background-image-in-firefox – mrmoment Aug 08 '14 at 02:08

1 Answers1

2

You can "fake" the background-image opacity with pseudo-element on your:

nav{
  position:relative;
}

nav::before{
  content: "";
  background: url(/img/xnav.jpg);
  background-origin:border-box;
  background-position:top;
  background-repeat:repeat;
  background-size:50px 50px;
  opacity: 0;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  position: absolute;
  transition: opacity 1s ease-in-out;
}

.contrast{ // applied on nav::before
  opacity: 1;
}

Thanks to Nicolas Gallagher for this.

Jo Liss
  • 30,333
  • 19
  • 121
  • 170
Alon Dahari
  • 1,138
  • 1
  • 9
  • 27
  • Thanks for the tip, this works well - however, it took some changing of the JS as you cant use JS to manipulate pseudo elements directly. Some CSS trickery fixes this. Also have to be careful with z-index values. The background won't display properly in some browsers, but I was able to fix this by setting a z-index:-1 on the pseudo elements AND z-index:0 on the nav element (works for IE and Moz) – George43g Aug 08 '14 at 04:21