Mark Smith
Mark Smith

Reputation: 315

CSS Clip - Sprite Image

I have a sprite image which I want to display 128x89px portions across multiple span elements.

In the example I have set the left-clip to 30px to highlight the issue, normally this would be in multiples of 128px. When I set the left clip to 30px, it seems to add 30px left margin. Surely, I don't need to add a negative left margin to correct it?

I am a total newbie to clip as I have never really needed to use it, but now there is. My understanding of it is the same as a square cut out of a piece of paper. Adjusting the clip values will move the piece of paper around therefore changing the viewed image.

Please help.

JSFiddle: http://jsfiddle.net/VgjXr/

CSS:

a {  
    border: 1px solid #000;  
    height: 89px;  
    width: 128px;  
    display: block;  
}
span.image {  
    background-image: url('http://i1269.photobucket.com/albums/jj591/mark1979smith/splice.jpg');  
    position: absolute;  
    display: block;  
    width: 128px;  
    height: 89px;  
    clip: rect(0px,158px,89px,30px);  
    clear: both;  
}

HTML:

<div class="element" id="cheeseOption7">   
    <div id="optional_46">
        <a href="#">                    
            <span class="image"><!--  --></span>
        </a>
    </div>
</div>

Upvotes: 1

Views: 3368

Answers (1)

ScottS
ScottS

Reputation: 72261

The best explaination I have found on clip is at this site, though I think you do have a generally correct grasp of how it works. What you are not grasping is how that relates to your situation. The clip is occuring on the background image of the span. Your 30px is telling the browser to clip off the image 30px from the left (which is exactly what your fiddle example is doing), but it does not affect the positioning of the background.

Using sprites, one does not normally use clip, but background-position to switch sprite image position in relation to the element it is displayed in. So for your 128px x 89px sprite images, you would start with background-position: 0 0 and move to -189px 0 to shift one image to the right or 0 -89px to shift one image down.

I assume because clip requires position: absolute is why you are using the span, but in fact, because you really should use background-position, it will allow you to eliminate the span all together, and just do the positioning on the background of the a element directly.

Upvotes: 3

Related Questions