Search code examples
htmlcssiconsvertical-alignment

Vertically align an image included using CSS background property to a Span tag


I have a span tag. I'm loading an image inside this span tag using css. Now I wants to vertically centre this image inside the span tag. I can't vertically centre this image because I'm applying this image to span using CSS. Here I'm using an icon sprite and extracting only relevant part from the icon-sprite. Can anyone help?

HTML

<span class="icon"></span>

CSS

.icon{
   background: url(../images/icon-sprite.png) no-repeat -328px 0;
   width: 60px;
   height: 40px;
   position: absolute; 
}

I tried adding line-height to .icon class. But no joy.


Solution

  • You will need to change the numbers in order for it to work for your icon, but this should do the trick.

    .icon { 
      position: relative;
      border:1px solid #FF0000;
      white-space: nowrap;
    } 
    
    .icon:before{
      content: "";
       position: relative;
       width:15px;
       display:inline-block;
    }
    
    .icon:after{
        content: "";
        position: absolute;
        top: 50%;
        left: 0; 
        margin-top: -8.5px;
        width: 15px;
        height: 18px; 
        background: url('https://www.google.com/images/nav_logo127.png') no-repeat -0px -327px;
    
    }
    <span class="icon" style="font-size:20px;">whatever</span>
    <span class="icon" style="font-size:25px;">whatever</span>
    <span class="icon" style="font-size:30px;">whatever</span>
    <span class="icon" style="font-size:35px;">whatever</span>
    <span class="icon" style="font-size:40px;">whatever</span>
    <span class="icon" style="font-size:45px;">whatever</span>

    The border and font size are just for the example.