简体   繁体   中英

Is it possible to use CSS hover properties on background-images?

I have an image on a site using the <img> tag, but I want the image to be nested inside of a div using the 'background-image' property instead.. problem is that the image has a :hover property on it that I have to keep. Can I place hover effects on a background-image?

Edit: Specifically what I'm looking for is to use this fancy webkit stuff activated by scrolling over the div that will affect , turning it from a b&w image to color. 激活,将其从黑白图像转换为颜色。 I have this working now with with the image sitting in an actual tag, but I don't know how to get this to work via ':hover'

For example:

div.cell:hover img{
opacity:1;
filter: url(filters.svg#grayscale); /* Firefox 3.5+ */
filter: gray; /* IE6-9 */
webkit-filter: grayscale(1); /* Google Chrome, Safari 6+ & Opera 15+ */
opacity:0.4;
}

this works fine and good with an image nested inside the tag, but if I do this

        .A1 {background-image:url('spindrift.jpg'); background-size:cover;}

then obviously the hover effect isn't going to work. How can I use hover effects on a background-image?

Sounds like you have something like this currently:

<div class="wrapper">
    <img class="theImage" src="theImage.png"/>
</div>

And you currently have a hover on the image:

.theImage:hover {
  background-color: red;
}

As Jakub said in a comment, you can move the image to be a background image, and simply add a hover to the div itself:

<div class="wrapper"></div>

.wrapper {
  background-image: url('theImage.png') no-repeat center;
}

.wrapper:hover {
  background-color: red;
}

Yes this is possible as you are placing the properties on the element that contains the background-image. Not the background-image on its own.

Just remove the image ( <img> ) and change the CSS so the .background element is being targeted. Then change the :hover to .background:hover so that the .background element is being targeted as well. The container div is just there to demonstrate its being 'nested'.

HTML

<div class="container">
    <div class="background"></div>
</div>

CSS

.background {
    background-image: url('path/to/img.jpg');
    width: 100px; /* width of the image */
    height: 100px; /* height of the image */
}
.background:hover {
    /* add new properties or change current ones */
}

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