如何在背景图像中居中文本

4

我真的很想做类似这样的事情...当我在左侧有图标的文本时:

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;
}

你能否发布一个链接,展示一下你得到的上述内容的图片? - gingerbreadboy
这更多是一个通用的事情...任何图像都可以搭配任何文本。 - redconservatory
3个回答

3

将你的标签的高度line-height设置为相同。像这样:

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

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

调整内边距?像素


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演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接