Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple HTML5/CSS3 background image transition on mouse hover

I'm trying to understand the simplest background transition possible using only HTML5 and CSS3. Searching through stackoverflow I've learned it can be easily implemented using external libraries such as jQuery but for this project I've decided not relying on any of those.

Markup

<nav> 
  <ul> 
    <li><a id="foobar" href="http://www.google.com/search?q=foobar">Foobar</a></li>
  </ul> 
</nav> 

Styles

body {
  background: url('background-default.png'), no-repeat;
}
#foobar a:hover {
   background: url('background-hover.png'), no-repeat;
  -webkit-transition: // TODO;
  -moz-transition: // TODO;
  -o-transition: // TODO;
  -ms-transition: // TODO;
  transition: // TODO;
}
like image 364
Nano Taboada Avatar asked Jan 19 '23 15:01

Nano Taboada


1 Answers

As I mentioned in my comment, you can't transition the background-image property but you can get the sort of effect you're looking for if you're willing to add extra markup and then transition the opacity. So you'll have some markup like this:

<nav>
  <ul>
    <li>
      <img src="no-icon.png">
      <img src="yes-icon.png">
      <a id="foobar" href="http://www.google.com/search?q=foobar">Foobar</a>
    </li>
  </ul>
</nav>

Then set the transition on the images, absolute position them (so they'll be like backgrounds), and hide one of them by default (I've left out the vendor extensions for clarity):

nav li img {
    position: absolute;
    transition-duration: 1.5s;
    opacity: 1;
}
nav li img:first-child {
    opacity: 0;
}

Then swap the opacity values on li:hover:

nav li:hover img {
    opacity: 0;
}
nav li:hover img:first-child {
    opacity: 1;
}

Here's a full working example. Not an ideal solution because you have to add extra markup, but it'll work.

like image 50
robertc Avatar answered Jan 23 '23 05:01

robertc