位置背景图像居中底部带有一些偏移量。

3
我希望将一个文字放在背景图像的底部并留有一些垂直偏移量。
例如:
同样的方法,我们可以这样做:
.img{
     background-position: 5px center; /* top + 5px */
}

我尝试着:

.img{
     background-position: -5px center; /* bottom - 5px ?? */
}

但是这个图片甚至不会显示出来。
我该如何做到这一点?(不需要知道元素的高度)
到目前为止,我的解决方法是将填充(图像大小)和边距(偏移量)应用于具有“position: bottom center;”属性的元素。
2个回答

1
使用:before和:after,您可以实现结果(使用精灵图像的确切位置)。
.img{
    position: relative;
}

.img:after {
    left: 50%;
    bottom: -5px;
    content: '';
    width: 32px;
    height: 32px;
    margin-left: -16px;
    position: absolute;
    background-position: 0 0;
}

.img:before {
    left: 50%;
    top: 5px;
    content: '';
    width: 32px;
    height: 32px;
    margin-left: -16px;
    position: absolute;
    background-position: -15px -30px;
}

1

不是用 CSS2,而是用 CSS3。使用 background-position,您可以给出一个 position 或者 negative 偏移。

您可以这样做:

JSFiddle演示

HTML

<div class="box"></div>

CSS(层叠样式表):
.box {
    width:300px;
    height:300px;
    background: url(http://placehold.it/100x100) no-repeat bottom -10px right -20px;
    border:2px solid red;
}

浏览器兼容性列表


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