Skip to content Skip to sidebar Skip to footer

Change Background Color And Image On Hover

I have a square with a logo inside. On hover in the square, I want the background color to change as well as the color of the logo. I have the following code:
Copy
.logo {
    width: 80px;
    height: 78px;
    text-indent: -9999em;
    background-image: url('http://s17.postimg.org/7hltqe5e3/sprite.png');
    background-repeat: no-repeat;
    background-position: 00;
    background-color: blue;
}
.logo:hover {
    background-color: red;
    background-position: -80px0;
}

http://jsfiddle.net/12u7ma2q/

Create a sprite with both versions of the logo side-by-side. When you hover you will change the background color and shift the position of the sprite image (left, right, up, down - depends on how you created your sprite).


The benefits to this answer over sailens is that you're not using invalid markup (<img> without a src attribute) and you're only making a single request for an image instead of two. Oh, and less markup - a single <div> (which could be an <a>, <span> etc).

You could also shorten .logo by using background instead of individual background properties. I listed them out at first for clarity.

.logo {
    width: 80px;
    height: 78px;
    text-indent: -9999em;
    background: blue url('http://s17.postimg.org/7hltqe5e3/sprite.png') no-repeat 00;
} 

http://jsfiddle.net/12u7ma2q/1/

Solution 2:

Cleaner HTML (since img tag needs a source, you can change it for a div):

<div class="pure-u-1 pure-u-md-1-3">
  <divclass="project", id="project1"><divclass="pure-img"></div></div>

And the CSS:

.project {
  background-color: #f5f4f4;
  margin: 00.5em2em;
  padding: 4em4em;
}

#project1:hover {
  background-color: red;
}

.pure-img{
    background-image: url(http://dummyimage.com/600x400/000/fff);
    width: 80px; 
    height: 78px;


}

#project1:hover.pure-img {
  background-image: url(http://dummyimage.com/600x400/666/0011fc);
}

and the fiddle http://jsfiddle.net/h6gwwox6/1/

Post a Comment for "Change Background Color And Image On Hover"