leonardeveloper
leonardeveloper

Reputation: 1853

How to make background image on hover have a transition effect without default background image?

So i'm doing a transition effect on an <a> that has no default background image so when I try to hover over it the transition effect doesn't work. I doubt that without having a default background image it'll not work. So how can I achieve my goal or any alternative on doing that without using javascript? Here is my code:

    <nav>
      <li><a href="products.html">Products</a></li>
    </na>

Here is my css:

    .nav>li>a { font-size:17px;  color:#929799; padding:45px 25px 35px 25px;
        -webkit-transition: background-image 1s ease-in-out;
        -moz-transition: background-image 1s ease-in-out;
        -o-transition: background-image 1s ease-in-out;
        transition: background-image 1s ease-in-out;
    }

    .nav>li>a:hover, .nav>li>a:focus{ 
      background:url(http://cdn.myld.com.au/2/1198/web_total-gardens_9a0e4cf244.png) no-repeat top center; color:#38c867; }

Upvotes: 0

Views: 5338

Answers (2)

Mohamed Rihan
Mohamed Rihan

Reputation: 119

css transition opacity allow image to change values over a specified duration, animating the property changes

http://css3.bradshawenterprises.com/cfimg/ or try

transition: all 1s ease-in-out;

Upvotes: 0

Turnip
Turnip

Reputation: 36652

background-image is a non-animatable property. You can not apply transitions.

I'm assuming you want to fade in the image on hover (?). A way to fake it is to apply your background image to a pseudo element and transition the opacity:

body {
  padding-top: 50px;
}

nav>ul>li>a {
  font-size: 17px;
  color: #929799;
  padding: 45px 25px 35px 25px;
  position: relative;
}

nav>ul>li>a>span {
  position: relative;
}

nav>ul>li>a:before {
  content: "";
  background: url(http://placehold.it/200x100) no-repeat top center;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  opacity: 0;
  transition: opacity 1s ease-in-out;
}

nav>ul>li>a:hover:before,
nav>ul>li>a:focus:before {
  opacity: 1;
}
<nav>
  <ul>
    <li><a href="products.html"><span>Products</span></a></li>
  </ul>
</nav>

As @GabyakaG.Petrioli mentioned in the comments, your selectors are wrong and you have invalid HTML. Both are fixed in the above example

Upvotes: 1

Related Questions