Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
117
rated 0 times [  123] [ 6]  / answers: 1 / hits: 22684  / 11 Years ago, thu, august 29, 2013, 12:00:00

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
Now I have some divs where I want to place these cards .
enter



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



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 !


More From » html

 Answers
3

You can achieve this using the background-size property, although the results might not be too pretty, since it stretches the background image.



So, if you know that your sprite is 13x5 cards exactly in size, you can give the cards background-size: 1300% 500% and then size them any way you want, since the background itself will scale accordingly.



Example



JSFiddle: http://jsfiddle.net/uLnzc/.



HTML



<!-- Hearts --->
<div class=card card-hearts-2></div>
<div class=card card-hearts-3 card-wide></div>
<div class=card card-hearts-4 card-high></div>

<!-- Clubs -->
<div class=card card-clubs-q></div>
<div class=card card-clubs-k card-wide></div>
<div class=card card-clubs-a card-high></div>


CSS



.card {
width: 81px;
height: 117px;
background: url('http://i.stack.imgur.com/WZ9Od.gif') no-repeat;
background-size: 1300% 500%;
}
.card-wide {
width: 100px;
}
.card-high {
height: 130px;
}

/**
* Backgrouns position of all the cards
*
* x offset in %: i * (100/x); i = 0, 1, ..., (x - 1); x = the number of cols in the sprite
* y offset in %: j * (100/y); j = 0, 1, ..., (y - 1); y = the number of rows in the sprite
*/

.card-hearts-2 { background-position: 0 0; }
.card-hearts-3 { background-position: 8.33% 0; }
.card-hearts-4 { background-position: 16.667% 0; }
/* ... */

/* ... */
.card-clubs-q { background-position: 83.333% 50%; }
.card-clubs-k { background-position: 91.667% 50%; }
.card-clubs-a { background-position: 100% 50%; }


You can read about offsetting backgrounds in percentages at MDN.



JSFiddle: http://jsfiddle.net/uLnzc/.


[#76049] Wednesday, August 28, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harleyterryp

Total Points: 290
Total Questions: 92
Total Answers: 95

Location: Montenegro
Member since Sun, May 7, 2023
1 Year ago
;