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 . Now I have some divs where I want to place these cards .
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 .
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 !
I would suggest having 2 sprites, mainly because you have a smaller resolution in your example sprite then would look good in the example div.
Alexander Wallin's answer is great! But I believe there is a small error in the formula for computing the percentage offset; where 100 is divided by x, it should be divided by (x-1):
PS: Sorry for making this comment as an answer. I do not have the necessary credits for making comments.
Another solution is to create an SVG and assign
class
attributes to the different path groups (each representing/rendering a card). If all path groups haveposition: absolute
anddisplay: none
, you could show only the path group matching the container card element and stretch it to full width and height with pure vector resizing.This will generate huge amounts of markup, so the best thing here would probably be on SVG per card.
Chris Coyier has an excellent article about using SVGs.
Example
HTML+SVG
CSS
For a regular image
max-width: 100%
andMax-height: 100%
should force the image to resize to the div.For a background-image
background-size: 100%
should work.Hi this is the easiest way of doing what you are after!
CSS -
HTML -
This will load your image once and set it up ready to be resized!
http://jsfiddle.net/j3xXe/10/
Regards
Alphanu
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
CSS
You can read about offsetting backgrounds in percentages at MDN.
JSFiddle: http://jsfiddle.net/uLnzc/.