将使用CSS background属性包含的图像垂直对齐到Span标记

时间:2016-12-27 12:30:09

标签: html css icons vertical-alignment

我有一个span标签。 我正在使用css 在此span标记内加载图片。 现在我想将此图片垂直居中于span标记。我不能垂直居中这个图像因为我正在使用CSS来应用这个图像。在这里,我使用了一个图标精灵,只从icon-sprite中提取相关部分。有人可以帮忙吗?

HTML

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

CSS

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

我尝试将行高添加到.icon类。但没有快乐。

3 个答案:

答案 0 :(得分:1)

您需要更改数字才能使其适用于您的图标,但这应该可以解决问题。

.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>

边框和字体大小仅用于示例。

答案 1 :(得分:0)

可以使用任何人:

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

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

答案 2 :(得分:0)

理想情况下,您应该有一个父类,并尝试将.icon垂直对齐父母。

&#13;
&#13;
.parent {
  position: relative;
  width: 120px;
  height: 80px;
}
.icon {
  background: url(../images/icon-sprite.png) no-repeat -328px 0;
  width: 60px;
  height: 40px;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  margin: auto;
  text-align: center;
}
&#13;
<div class="parent">
  <span class="icon"></span>
</div>
&#13;
&#13;
&#13;