Show background image on mouse

I have the following HTML:

<a href="#" class="home-block" style="background-color:#464646; background-image:url('wardrobe.jpg')">Wardrobe</a> <a href="#" class="home-block" style="background-color:#6a0d1f; background-image:url('wine.jpg')">Wine</a> <a href="#" class="home-block" style="background-color:#291407; background-image:url('coffee.jpg')">Coffee</a> 

This is the appropriate CSS:

 .home-block { background-color: #c2b89c; display: block; height: 180px; line-height:180px; text-align: center; font-size: 70px; color:#e2e2e2; text-shadow: 2px 2px 0 #444; margin-bottom: 20px; background-size: cover; background-position: center center; box-shadow: 1px 1px 4px #111; } 

Now my result looks something like this:

enter image description here

This is fine, but I really want the blocks to be solid and only display the image on hover. For instance:

enter image description here

Please keep in mind that I am using a responsive design, so the blocks will have different sizes and aspect ratios on different screen sizes. This is why I use background-size: cover . This is also for the CMS system, so I want the images and colors to be set embedded in the HTML, so they will be easily editable and more blocks can be added.

Thus, I basically need a clean solution without absolute positioned elements (because they tend to break if there is no fixed width) to achieve this.

I tried this:

 .home-block { background: none; } .home-block:hover { background: inherit } 

but without success. I was just about to fix all this with some jQuery lines, but I just wanted to check if there was a pure CSS method for this.

+4
source share
2 answers

This is a bit tricky if you need background-image set inline to HTML. You cannot easily overwrite it. I would try changing the background-position to hover:

 .home-block { ... background-position: 1000px 1000px; // background-image is there but not visible } .home-block:hover { background-position: center center !important; // make it visible } 

http://jsfiddle.net/h2Jbg/

So, for the normal state, you will not see the background image, but you will see the color backgroud. When you hover over the mouse, you move the image back.

+6
source

Unfortunately, it is not possible to use the built-in pseudo-class :hover , which makes it difficult to execute this line in a single element.

It is often exciting to use an additional element for styling, but at least this is a possible solution to the problem.

 <div style="background-image: url(http://lorempixel.com/400/200);"> <div class="home-block">Foo</div> </div> 

Then you can use something like this in your CSS:

 .home-block:hover { background: transparent; } 

Demo

Thus, you can add new blocks with separate background images without updating the stylesheet.

+4
source

All Articles