Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css sprite as background, limited portion?

Tags:

css

image

sprite

I need to place an icon of 48x48 as background. I have this icon in my image sprite where of course there are many other images.

Is there a way to show as background only a porition of the image?

thanks

EDIT: Is there a way to do this without setting width-height of the backgrounded element? (I am not sure if acutally i can set a width-height)

Edit2: this is what i need: http://jsfiddle.net/pdxnj/

Thanks

like image 234
dynamic Avatar asked Nov 06 '22 00:11

dynamic


1 Answers

Set the width and height of the element to 48px.

.element{
    width: 48px;
    height: 48px;
}

Set the background of the element to your image

.element{
    background-image: url('image.png');
}

Move the background so that the top left corner of the icon is positioned correctly.

.element{
    background-position: 20px 94px;
}

The two numbers in background-position are the X and Y coordinates (respectively) where the top left corner of your 48px by 48px is in your sprite image. So maybe it's actually 96px 0px or something.

EDIT

If you can't control the width and height of the element you are trying to put the background in, but you can add new DOM elements, you can try adding a span inside the element you really want to put the image as a background for.

It would look something like:

<div id="noControl">
    <span id="justCreated">
    </span>
</div>

and the CSS would look exactly the same as above, except you would need to treat the inline span as a block element:

#justCreated{
    display: inline-block;
}

EDIT 2

If you have control over new DOM elements, and want to make your sprite the background without messing with a span, just add another div inside your original one.

Would wind up looking like:

<div id="noControl">
    <div id="justCreated">
        ALL of the content that used to be inside #noControl
    </div>
</div>

and the CSS for it would be

#justCreated{
    width: 48px;
    height: 48px;
    background-image: url('image.png');
    background-position: 96px 0px;

    z-index: -200;
    /* z-index of all the contents needs to be not set, or set to larger than -200 */
}

This is all theoretical, but it SHOULD work.

This way, you can apply the sprite sizing to a block element without messing with the inline stuff. This may affect CSS if it addresses elements by child status (like #noControl > a), because you are inserting a div between the parent and the child.

I am still researching whether you can do this at all if you have no control over the DOM at all.

like image 79
rockerest Avatar answered Nov 09 '22 05:11

rockerest