CSS Sprites - using only one image fragment as background for part of an element

I am using CSS Sprite Technique with a background image that looks something like this:

enter image description here

CSS code for 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 as follows:

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

I want to add text inside my icons, for example:

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

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

enter image description here

Question: how can I use only part of the image as a background image for part of my element?

Notes:

  • width - 16px for div.icon does not help.
+7
source share
4 answers

You have two ways:

1) Your markup should look something like this:

 <div class="icon warning"></div><div class="txt">There is a warning on this page</div> .icon {width:10px(for ex.)} 

2) You must change the image. The icons in the image should be below the other.

+6
source

Remember, wherever possible, you should not change your layout just to achieve the design. You can use 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; } 
+7
source

Sorry, my previous answer was unsuccessful, though from.

Edit: If you have 16px padding, you should set the width to 0, not 16px. And I have problems when the :not(:empty) bit works in all browsers; better get rid of him. Thus, CSS becomes:

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

jsFiddle

+3
source

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

-one
source

All Articles