html - CSS Sprites - 仅使用一张图像作为元素的一部分的背景

标签 html css css-sprites

我使用 CSS Sprite Technique背景图片看起来像这样:

enter image description here

图标的 CSS 代码:

div.icon {
    background-color: transparent;
    background-image: url("/images/icons.png");
    background-position: 0 0;
    background-repeat: no-repeat;
    display: inline-block;
    height: auto;
    vertical-align: text-top;
    width: auto;
}
div.icon:empty {
    width:16px;
    height:16px;
}
div.icon:not(:empty) {
    padding-left:20px;
}
div.icon.attenuation {
    background-position: 0 0;
}

我的图标可以这样使用:

<div class="icon warning"></div>

我想在图标中添加一些文字,例如:

<div class="icon warning">There is a warning on this page</div>

但问题是背景图片覆盖了整个文本区域:

enter image description here

问题是:我怎样才能只使用图像的一部分作为我元素的一部分的背景图像?

注意事项:

  • div.iconwidth 设置为 16px 没有帮助。

最佳答案

请记住,只要有可能,您不应该仅仅为了实现设计而更改标记。可以使用您的标记。

div.icon:before {
    content: "";
    background-color: transparent;
    background-image: url("/images/icons.png");
    display: inline-block;
    height: 16px;
    vertical-align: text-top;
    width: 16px;
}

div.icon:not(:empty):before {
    margin-right: 4px;
}

div.icon.attenuation {
    background-position: 0 0;
}

关于html - CSS Sprites - 仅使用一张图像作为元素的一部分的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10481632/

相关文章:

css sprite 图像位置

javascript - 用纯 JavaScript 创建导航和页面

css - 如何扩大 R DT 包中的数据表?

html - 居中可缩放图像(用于极其简单的网络)

html - 如何防止 DIV 与右侧 float 图像重叠?

jQuery 优化对悬停事件属性的访问

html - 将元素放在中心

c# - html5和C#之间的web socket通信

java - 使用 java 修改 HTML

css - 新上传后 Sprite 没有改变