0

I am trying to get css sprites to work. My image consists of two parts. The left part is black and the rigt part is white.

The code below shows the white part of the image. If i change the -40px value to 0 in #item0, it displays the both the black and the white part.

I cannot get it to just show the black part of the image. Can you spot what i am doing wrong?

<style type="text/css">
    #menu-left {            
        width: 200px;
        background-color: #73b2d6;

    }

    #navlist li {
        list-style: none;
        padding-left: 10px;
        width: 190px;
    }

    #navlist a {
        width: 150px;
        height: 44px;
        padding-left: 40px;
        padding-top: 20px;
        display: block;
        width: 100px;
    }

    #item0 {
        background: url('http://www.fabian.dk/all.png') -40px 7px no-repeat;
    }
</style>

<div id="menu-left">
    <ul id="navlist">
        <li id="item0"><a href="#">link 1</a></li>
    </ul>
</div>
Tony
  • 1,394
  • 5
  • 22
  • 48

2 Answers2

1

Unfortunately it cannot be done with the DOM-structure you have, in a way that I can think of. Since the li-element is larger than the background, it is not possible to cut of the right part of an image like that.

The easiest thing I can think of is to add an additional element within your li element, with a fixed size, and apply the background to that element instead of the entire li.

HTML:

<div id="menu-left">
    <ul id="navlist">
        <li id="item0"><div></div><a href="#">link 1</a></li>
    </ul>
</div>​

CSS:

#navlist li div {
    background: url('http://www.fabian.dk/all.png') 0 7px no-repeat;
    width: 40px;
    height: 40px;
    float: left;
}​

Working example

Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103
0

Alternatively you can use the :before pseudo class.

#item0:before {
        background: url('http://www.fabian.dk/all.png') 0 7px no-repeat;
        content : '';
        height: 40px;
        position: absolute;
        width: 40px;
    }
Jared
  • 12,406
  • 1
  • 35
  • 39