CSS Sprites – using just one piece of an image as a background for part of an element

I use the CSS Sprite Technique with a background image that looks something like this:

The CSS code for the icons:

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

My icons can be used like this:

I want to put some text inside my icons like:

There is a warning on this page

But the problem is that the background image covers the entire text area:

The question is: how can I use only part of an image as a background image for part of my element?

Notes:

  • setting width to 16px for div.icon doesn’t help.

Problem courtesy of: AlexStack

Solution

You have two ways:

1)Your markup must be like this:

There is a warning on this page
.icon {width:10px(for ex.)}

2)You must change the image. Icons in the image must be below the another

Solution courtesy of: jumancy

Discussion

Sorry, my previous answer was not well though out.

Edit: If you have a 16px padding, you should set the width to 0, not 16px. And I’ve got troubles getting the :not(:empty) bit to work on all browsers; better get rid of it. So the CSS becomes:

.icon {
  ...
  width:0; height:16px; padding-left:16px;
}
.icon:empty {
  width:16px; padding-left:0;
}

jsFiddle

Discussion courtesy of: Mr Lister

set width: 16px; height: 16px; overflow: hidden; text-indent: -9999em; and remove padding

Discussion courtesy of: simoncereska

Remember, where ever possible, you shouldn’t change your markup just to achieve a design. It is possible using your markup.

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

Discussion courtesy of: Alex Chamberlain

This recipe can be found in it’s original form on Stack Over Flow .

稿源:CSS3 Recipes (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » CSS Sprites – using just one piece of an image as a background for part of an element

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录