Resizing background sprite image to fit div

2019-03-11 08:12发布

I am creating a card game . I have a sprite image of cards . Say in the sprite , each of the cards is 50px wide and 80px high . enter image description here Now I have some divs where I want to place these cards . enter image description here

Say the Divs are 100px wide and 160px high .

I have using the first image as a Sprite for the Divs like in the below.

background: url(../images/poker_sprite.gif) no-repeat scroll 0 0 transparent ;

I vary the x and y positions so that different divs get diff cards .

What CSS property do I use to make the background image fit to the Div ? I am not allowed to change the size of the Sprites or the Div .

Now I am going to Drag these cards and place them into some slots as marked 1-13 below . enter image description here

So the card div will have variable width . The background image will need to resize to fit in the variable width div . How do I go about doing this ? Should I used multiple sprites of various sizes?

Thanks !

7条回答
Melony?
2楼-- · 2019-03-11 08:41

This will do what I believe you are looking for and should be supported for all browsers.

Say you want a king in a specific slot what you would do is place these two classes in your css.

.king{
    width: 50px;
    height: 80px;
    position: relative;
    background-position: 50px 0px;
    background-image: url(http://i.stack.imgur.com/WZ9Od.gif);
}
.play-area{
    width: 50px;
    height: 80px;
    position: absolute;
}

Now for the html you just need

<div class="play-area">
    <div class="king"></div>
</div>

All you need to do is play around with the numbers so the borders of the cards displayed come out correct.

Here's the fiddle: http://jsfiddle.net/j3xXe/4/

查看更多
登录 后发表回答