简体   繁体   中英

background-image transition for div on hover is not working

I have a div that I want to have a transition effect on hover.

I put together the following CSS code, but the transition is not working in chrome nor firefox.

 #header { border: 0.1px solid #666; background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0)); height: 10vh; padding: 0; transition: background-image 1s ease-in-out; /* NOT WORKING */ -webkit-transition: background-image 1s ease-in-out; /* NOT WORKING */ } #header:hover { background-image: linear-gradient(rgba(0, 0, 0, 0.75), rgba(0, 0, 0, 0.0)); } 
 <html> <body> <div id="header"> this is my header</div> </body> </html> 

Am I doing anything wrong?

Would be great if anyone could help!!

Many thanks

CSS gradients do not support the transition property.

In your case, you can create a similar effect by using a pseudoelement and transitioning its opacity on hover instead.

 #header { border: 0.1px solid #666; height: 10vh; padding: 0; position: relative; } #header:before { content: ''; position: absolute; left: 0; top: 0; width: 100%; height: 100%; opacity: .5; transition: opacity 1s ease-in-out; background: linear-gradient(black, transparent); } #header:hover:before { opacity: .75; } .logo { color: white; position: relative; } 
 <div id="header"><div class="logo">LOGO</div></div> 

You cannot apply transition on background-image like this. You need to apply transition on another property. You can for example use multiple gradient on your background and apply transition on background-size :

 #header { border: 0.1px solid #666; background-image: linear-gradient(rgba(0, 0, 0, 0.75), rgba(0, 0, 0, 0.0)), linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0)); background-size: 100% 0% , auto; background-repeat:no-repeat; height: 10vh; padding: 0; transition: background 1s ease-in-out; -webkit-transition: background 1s ease-in-out; } #header:hover { background-size: 100% 100%, auto; } 
 <div id="header"> this is my header</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM