First Item
  • Long Item
  • Sprite central background image

    I have a menu as follows:

    <ul> <li><a href="#">First Item</a></li> <li><a href="#">Long Item</a></li> <li><a href="#">Very very short Item</a></li> <li><a href="#">Another Item</a></li> <li><a href="#">Last Item</a></li> </ul> 

    I would like to use a sprite image as a background in CSS. I would like the image to be concentrated in different width menu items. Currently, the first element has the correct CSS:

     background: url(images/sprite.png) no-repeat -20px -10px; 

    For the second:

     background: url(images/sprite.png) no-repeat -24px -10px; 

    For the third:

     background: url(images/sprite.png) no-repeat -32px -10px; 

    And so on. I do not know the exact width of each element, and it can change at any time.

    I have access to the HTML structure, so I can add tags if necessary. Is it possible to center the background image in this case?

    +4
    source share
    2 answers

    JSFiddle demo .

    Basically, you create a pseudo-element, use position: absolute and left:50% to center it.

     li a { position: relative;} /* makes the (position:absolute) below work */ li a:after{ content: ""; position: absolute; top: 0; left: 50%; /* centers the left edge of the sprite */ margin-left: -8.5px; /* this centers the actual sprite--this is half the sprite-window width. if you don't do this, the left edge will be centered instead of the center of the sprite. */ width: 15px; /* set window to see sprite through */ height: 18px; /* set window to see sprite through */ background: url(https://www.google.com/images/nav_logo129.png) no-repeat -15px -327px; /* set up the sprite. Obviously change this fto make each one different. */ } 
    +12
    source

    If the background image is a vertically aligned sprite sheet, you can center each sprite horizontally as follows:

     li a { background-image: url(images/sprite.png); background-repeat: none; background-position: 50% [y position of sprite]; } 

    If the background image is a horizontal oriented sprite sheet, you can vertically center each sprite as follows:

     li a { background-image: url(images/sprite.png); background-repeat: none; background-position: [x position of sprite] 50%; } 

    If your sprite sheet is compact or you are not trying to center the background image in one of the above scenarios, these solutions do not apply.

    +1
    source

    Source: https://habr.com/ru/post/1489167/


    All Articles