tags:

views:

34

answers:

1

I am replacing most inline images on my sites with a sprite.

The sprite class would contain some basic css:

.sprite{
background-image:url(...);
background-position:...;
width: 16px;
height:16px;
}

I saw that nesting div inside of an anchor tag is not a good idea.

<a><div class="sprite"></div></a>

I've tried to add sprites to span elements instead.

<a><span class="sprite"></span></a>

But the span elements do not expand to the width and height that I set. It would be really useful to be able to use span elements to replace image tags with a sprite. I could add a blank gif image into the span element to expand it. But that would defeat the reason why I want to use sprites (to reduce the number of http requests).

Using div elements inside an anchor tag is not correct.

So how can I use sprites inside an anchor element?

And there also is always the problem of aligning the div. If an image is centered in another element, how do I replace it with a sprite?

+2  A: 

You need to declare display: block; on your span elements which are by default inline elements. Something like:

.sprite{
    display: block;
    background-image:url(...);
    background-position:...;
    width: 16px;
    height:16px;
}

That should make the span elements expand to your desired width/height.

Hope this helps !

FreekOne
Can we add a `width` or `height` to an inline element like `span` or are we simply converting it into `div` by using `display: block`?
Swanand
You're pretty much just converting it to a `div`.
Kyle Sevenoaks
Yes, you can add width and/or height properties to the span, but they will be ignored unless you change its behavior, which is where `display: block;` comes into play, and no, the element is not being "converted" -- it's still a `span` -- but rather its default behavior is being changed and it will behave like a `div`. Hope that makes sense.
FreekOne
That solves the problem with not using div elements in an anchor tag. But it still brings a problem with centering the image in a parent element.
reggie
Since you have a fixed size for the element, you can always define the background's position in pixels relative to the element's top-left corner and center it "manually". However, there is no way of cropping a portion of a sprite through CSS in order to use it as a background in an element which is wider and/or taller, and the only solution (for non-repeating backgrounds only) is to leave enough empty space on the bottom-right side of that sprite so it would clear its element's right and bottom margin.
FreekOne
Anyways, if you want my honest opinion, unless you're doing rounded corners that *require* the use of images, using sprites for backgrounds simply isn't worth the hassle, not to mention that in some cases (a repeating background) it's impossible to begin with.
FreekOne