将元素中的背景图像位置与图像精灵中的位置相结合

Combine the background image position in the element with position in the image sprites

我有一个元素 (h3),我想将背景位置设置在右边,很简单:

background: url('/images/icon-popular.png') no-repeat right center;

但我想在有很多其他图标(图像精灵)的地方使用 .png 文件,通常我会这样做:

background-image: url('/images/icons-info.png');
background-position: 0 -110px;

如何将文件中的背景位置与元素中的 "right center" 位置合并?

这里有一个与您相似的主题:Using Css Sprites and background position

但就我个人而言,我将使用像 h3:before 这样的伪选择器来实现这种效果,将其设置为与 sprite 中图标的大小相匹配,并将该元素放置在 h3.

h3 {
    background-color: #faa;
    padding:5px 10px;
}

h3:before {
    float: right;
    display: block;
    content: "";
    width: 35px;
    height: 23px;
    background: transparent url('https://jsfiddle.net/img/logo.png') no-repeat left top;
}

https://jsfiddle.net/3sdj4tga/

您的方法可能存在的问题是,如果 h3 比您在 sprite 中分配的 space 多,图像的其他部分将显示出不良效果。