treehouse : what would you like to learn today?
Web Design Web Development iOS Development

background image with responsive design

  • I am using twitter bootstrap for my responsive site and have run into a bit of a roadblock. I am trying to use the old sprite hover technique as follows:

    .featuredimg{background: url('[imgUrlHere]');width:370px;height:430px;display: block;}
    .featuredimg:hover{background: url('[imgUrlHere]')0px -430px;}
    

    It's pretty straightforward. You hover and the image moves up 430px to reveal the bottom half. The problem is that it isn't responsive AT ALL (the image always stays the same width and height regardless of window width).

    I've searched the web for a while now looking for a solution to what should be a common problem to no avail. Any chance we can solve this here?

  • Could you do something with background-size?

    IE9+

    I confess, I'm not sure how this works for sprites and fixed pixel widths.

  • Well there is background-size:cover but that is generally used for full screen scalable background images that do not need a hover.

    I want to convert the widths to percentage but I'm not sure how to make this whole thing work while maintaining the responsive nature of the site.

  • background-size: cover can be used on any element.

    Not sure how the % would work out.

    My advice would be to try out a reduced test case in Codepen. I'm sure you'd get a lot of help as I think that we'd all like to see it.

  • Here is what I'm trying to achieve keeping in mind that the background img needs to scale.

    http://cdpn.io/KuDfj

  • Found a possible solution through jquery:

    $(".featuredimg img").hover(
                  function () {
                        $(this).attr("src", '/wp-content/themes/wordpress-bootstrap/img/products/qcbot/featured-hover.jpg');
                  }, 
                  function () {
                        $(this).attr("src", '/wp-content/themes/wordpress-bootstrap/img/products/qcbot/featured.jpg');
                  });
    
    });
    

    Working example here: http://jsbin.com/oriyef/1/edit

  • You can use background-size with simple sprites: http://jsbin.com/oriyef/2/edit