如何使用背景图像居中文本

时间:2012-03-06 16:33:46

标签: css

我真的想做这样的事情...当我在左边有图标的文字时,这就是:

enter image description here

我尝试(不成功)做一些事情:

    <a href="#" class="icon">Text centered vertically in relation 
to the background image</a>

CSS

a.icon {
background: url(image.png) 0 50%;
margin-top: -5%;
min-height: the-height-of-my-image-plus-the-negative-margin;
}

3 个答案:

答案 0 :(得分:3)

line-heightheight标记的a相同。像这样:

a.icon {
background: url(image.png) 0 50%;
margin-top: -5%;
height:40px;
line-height:40px;
text-align:center;
}

答案 1 :(得分:1)

a.icon {
background: url(image.png) 0 50%;
padding: ?px ?px
}

调整填充?px

答案 2 :(得分:0)

我想不出一个完美的解决方案,但以下代码可能有效。然而,它打破了锚点 - 链接规范,这是一个非常糟糕的做法。

CSS

<style type="text/css">
.fixinline {
 display: inline-block;
}
.icon { 
 background: red url(http://goo.gl/12gdn) no-repeat left center;
 height: 135px; /* >= image height */
 display: table;
 padding: 0 0 0 135px; /* >= image height */
}
.icon span {
 display: table-cell;
 background-color: yellow;
 vertical-align: middle;
}
</style>

HTML

<span class="fixinline"><a class="icon"><span>hello<br>there</span></a></span>

jsFiddle Demo

相关问题