Feres Hammemi
Feres Hammemi

Reputation: 39

how to fix CSS transition for a background-image on hover?

Am working in a School project to make an e-commerce website, I want to make a CSS transition on the navbar blocks ( the lis inside the ul ) like when I hover on a block the background-image of that block shows up, but it seems the transition doesn't work and only the normal instant hover happens.

this is my code showing only one block of the navbar which is the catalogue:

#catalogue {
  -o-transition-property: all;
  -o-transition-duration: 2s;
  -o-transition-timing-function: ease-in-out;
  -o-transition-delay: 2s;
  background-size: cover;
  background-repeat: no-repeat;
}

#catalogue:hover {
  display: inline-block;
  margin-left: 70px;
  position: relative;
  background-image: url(f1.png);
  background-size: 125px 70px;
  color: #000;
  font-weight: 600;
}
<nav>
  <ul>
    <li id="home"><a>Home</a></li>
    <li id="catalogue"><a>Catalogue</a></li>
    <li id="news"><a>News&Trends </a></li>
    <li id="contact"><a>Contact us</a></li>
  </ul>

Upvotes: 3

Views: 14331

Answers (3)

Gwa Si
Gwa Si

Reputation: 335

I hope this helps.

#YourDIV {
    background-image: url(Yourimage.jpg) no-repeat;
}

#YourDIV:hover {
  background-image: url(Yourimage.jpg) no-repeat;
    background-size: 150%;
}

Upvotes: -1

hexangel616
hexangel616

Reputation: 356

You do not need to use opera (-o-) prefixes on your transition properties. CSS transitions do not require prefixes anymore: http://shouldiprefix.com/#transitions

Instead of transitions, for the background effect, you should use CSS animations - because as of today it isn't possible to apply transitions to background propreties.

li {
  transition: all 2s ease-in-out 2s;
  background-size: cover;
  background-repeat: no-repeat;
}

li:hover {
  margin-left: 70px;
  position: relative;
  background-size: 125px 70px;
  color: #000;
  font-weight: 600;
  animation: backgroundIMG 2s ease-in-out 2s;
  animation-fill-mode: forwards;
}

@keyframes backgroundIMG {
  100% { background-image: url(http://www.rayesdesign.com/glitters/blue/blue016.gif); }
}

See it running here: https://jsfiddle.net/Lkawnpg6/1/

Ps. I've changed the image for testing.

Upvotes: 2

StefanBob
StefanBob

Reputation: 5128

You can't transition a background-image like that.

You can try adding an extra div on top with the background (or a pseudo element :before or :after) and then transition it's opacity.

Normally you would transition a background-color like below

.box {
  display: block;
  width: 100px;
  height: 100px;
  background-color: green;
  transition: background-color 0.3s ease;
}

.box:hover {
  background-color: red;
}
<div class="box"></div>

Upvotes: 2

Related Questions