HTML and CSS Reference
In-Depth Information
LESS And Sass To e Rescue
With all of the images on the same square grid, we can now easily compute
the top-left coordinate of each image (this coordinate is the exact match
needed for the background-position values to reposition the sprite).
Just take the base size of the grid and multiply it by the numbers that you
just added to your reference image. Say you need to target the image at a
position of (5,3), and your grid size is 32 pixels; the top-left position of your
image will be 32 × (5,3) = (160,96). To add these values to your CSS file, just
use their negative equivalents, like so:
background-position: -160px -96px;
Leave your calculator where it is for the time being, because it would be too
much of a hassle. If computers are good at anything, it's doing calculations,
so we're going to make good use of that power. Plain CSS doesn't allow us
to do calculations (yet), but languages like LESS and Sass were made to do
just that. If you need more background information, check out the article “An
Introduction to LESS and Comparison to Sass.” While both languages o " er
similar functionality, their syntaxes are slightly di " erent. I'm a LESS man
myself, but if you're used to Sass, converting the following examples to Sass
code shouldn't be too hard. Now for some advanced CSS magic:
@spriteGrid: 32px;
.sprite(@x, @y) {
background: url(img/sprite.png) no-repeat;
background-position: -(@x*@spriteGrid) -(@y*@spriteGrid);
}
Nothing too exciting so far. First, we've defined the grid size using a LESS
variable ( @spriteGrid ) . Then, we made a mixin that accepts the numbers
we added to the reference image earlier. This mixin uses the grid variable
and the image's coordinates to calculate the base position of the image that
Search WWH ::




Custom Search