user1937021
user1937021

Reputation: 10771

responsive sprite background image, how to

Hi I have two columns of content within a container, the first column has text and the second is a span with a background sprite image. The problem is when I get to smaller screen resolutions, I want the background sprite image to have a width in percentage to be able to scale it along with the H5 with a percentage width, is there a way to do this?

h5{
    float:left;
    display:block;
    width:800px;
}

.sprite{
    background-image: url("assets/img/website_sprite_a.png");
    background-position: -60px -60px;
    float:left;
    display:block;
    width:64px;
}

<div class="container">
 <h5>Title
 </h5>
 <span class="sprite">
 </span>
</div>

Upvotes: 5

Views: 13446

Answers (2)

user3037131
user3037131

Reputation: 1

nearly a year too late, but I was trying to figure out the same and wasn't able to come up with or find a direct answer. After a little fooling around with multiple pieces of advice, I figured it out. Haven't had a chance to test this on IE8 yet, and stopped bothering with IE6/7, so please bear that in mind.

The trick I found is to use a combination of background-position (using percentages—of the sprite image—as mentioned before), padding-top (again, using percentages—this is the percentage of the total width of the sprite image), and background-size: cover.

Play around with it at jsfiddle.

#wrapper {
    position: relative;
    width: 100%;
}
.div {
    position: absolute;
    top: 0;
    left: 0;
    background-image: url('http://upload.wikimedia.org/wikipedia/en/2/2e/Sprite_logo.jpg');
    background-repeat: no-repeat;
    background-position: 0% 0%;
    background-size: cover;
    padding: 50% 0 0 0;
    width: 40%;
}

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

Upvotes: 0

Tomas Ramirez Sarduy
Tomas Ramirez Sarduy

Reputation: 17471

In your case I would go with a single background-image, but in the case you will have a lot of images or you really want to do this you can use the background-size property.

From MDN:

The background-size CSS property specifies the size of the background images. The size of the image can be fully constrained or only partially in order to preserve its intrinsic ratio.

.sprite{
    background-image: url("assets/img/website_sprite_a.png");
    background-position: -30% -30%; //use % instead pixels
    float:left;
    display:block;
    width:64px;
    background-size: 100%; //play with this
}

You also should read this:

I have played a little bit with this on JSFIddle. Resize the browser to see the effect.

Upvotes: 4

Related Questions