Search code examples
cssalignmentbackground-imagesprite

CSS Sprite Alignment in LI where images should be on the right


I can't seem to get the sprite to be aligned on right of the LI element

<li class="menuItems">
      <div style="background: #ffffff url('pixmaps/glyphicons.png') no-repeat 
-553px -56px; height:27px;width:29px;background-position: -30px 0px;">
        <a href="#"  >Streams</a>
    </div>
</li>

Weird alignment

I tried with and without the div - putting the sprite-background on the li or the a element but behaving almost the same. Changing the li's padding (a often read solution) would mess up my -Link, which should remain at this very position.

So what is the proper way to solve this? Sure I could modify the sprite and add a huge transparent space, but thats not really the way to go as my sprite includes the whole glyphiconset (400+ Icons + in addition all the Icons in a darker tone for rollover).

Thank you!


Solution

  • I was going to leave this as comment, but it's actually more of an answer.

    If you want to use an extra element, I generally use spans. Set it to display: block, with both the height and width set as well (to the exact size of the icon). If you don't want it to affect the layout, set it to position: absolute, and to position it, do something like right: 10px; top: 10px etc. If you use position: absolute, you'd also need to make sure the parent has positioning set too, like position: relative.

    Full example:

    .icon {
      position: absolute;
      display: block;
      width: 32px;
      height: 32px;
      top: 4px;
      right: 4px;
      background: url('pixmaps/glyphicons.png') no-repeat -553px -56px; /* set the offset to the exact position of your icon */
    }
    
    .menuItems {
      position: relative;
    }