I'm putting together a sprite and have two questions.
Something I've always wondered whether possible is negatively positioning a background picture to the right or bottom. A negative position is bread and butter stuff on the left of an element or top but what about the right and bottom?
If I have a 500px by 500px div can I then position the left edge of a background image to appear 5px in from the right using a negative value rahter than 495px to push it over?
The second question is whether I can use just a small portion of an image and repeat it without the rest of the image showing.
For example, I may have a sprite thats 300px square and filled with all kinds of things. Is it possible to take a 50px square portion of that image and repeat it in the background of an element?
I very much doubt either is possible but must put the monkey to sleep!
To "negatively positioning a background picture to the right or bottom", you can use percentages less than 0%. e.g.:
background-position: -11% -7%;
...positions the image cropped on the bottom right if the image is of similar size to the element. You might need more negative percentages if they aren't the same size.
To "negatively positioning a background picture to the left or top", you can use percentages greater than 100%. e.g.:
background-position: 105% 110%;
...positions the image cropped on the top and left assuming again that they are of similar sizes. You might need larger percentages if they aren't the same size.
Finding the exact percentages you need is not very intuitive, however. CSS uses percentages a little differently with background-position
. The value is the percentage along both the image and element (aka viewport) where they are the same. This is why 0%
is equal to left
, 50%
is equal to center
, and 100%
is equal to right
. Outside of this range it is even less intuitive as "less than zero" matches a point before the top/left edge on both the image and the element (effectively shifting the image away from the top/left), and "greater than 100%" matches a point greater than the far bottom/right edge which has the effect of moving the image away from the bottom/right.
These equation helps to determine where you want the image to sit. Simple algebra will get you the variable you want to know (e.g., solve for percentage).
effectiveLeft = (elementWidth - imageWidth) * percentageLeft;
effectiveTop = (elementHeight - imageHeight) * percentageTop;
As for your second question (repeating part of an image), I don't believe this is possible unless you were to repeat multiple cropping elements, which is different than what you were wanting.