CSS still does not offer a solution for background image cropping out of the box, so here’s a technique that makes use of pseudo elements that I use extensively for this purpose. What I basically did – I created a square 16×16 pixels pseudo element box ::before the content of the element, assigned background image to it, and then, based on features of the href atribute of each link, I defined background coordinates, so the correct icon is displayed depending on the file type (extension):
The Markup:
<ul class="css3-background-image-cropping">
<li><a href="some-file.md">some-file.md</a></li>
<li><a href="some-file.pdf">some-file.pdf</a></li>
<li><a href="some-file.txt">some-file.txt</a></li>
</ul>
The CSS:
:root .css3-background-image-cropping a::before
{
content: "";
display: inline-block;
vertical-align: middle;
margin: 0 4px 0 0;
width: 16px;
height: 16px;
background: url("icons.png") no-repeat;
}
:root .css3-background-image-cropping a[href$=".md"]::before
{
background-position: 0 -64px;
}
:root .css3-background-image-cropping a[href$=".pdf"]::before
{
background-position: 0 -80px;
}
:root .css3-background-image-cropping a[href$=".txt"]::before
{
background-position: 0 -96px;
}
The Icons Sprite
![]()
And voilà! That’s the result:
The Advantages
- The texts in the boxes wrap safely and nicely without revealing unwanted regions of the sprite.
- The images in the sprite are order- and size-independent.
The Disadvantages
- Works only on CSS3-capable browsers.
If you like this post, you can try the demo or download the example, follow me on Twitter or check my website for more cool stuff! Happy new year!
Relates Posts
- HTML5 Shopping Cart
- CSS3 Treeview. No JavaScript.
- HTML5 Resume Generator and Onepager Website
- CSS3 Driven Slides Viewer Without any JavaScript
- Fully Functional CSS3-only Tabstrip Without JavaScript
- Selecting only the first element occurence out of siblings with the same class name with CSS3
- How to Style Select Boxes with CSS3
- CSS3 Element Reflections
- CSS3 iPhone Toggle Buttons
- CSS3 Gaussian Blur Effect
- Fancy CSS3 Tooltips Without JavaScript
- Imageless Custom Checkboxes and Radio Buttons with CSS3

[...] CSS3 Background Image Cropping [...]
[...] CSS3 Background Image Cropping [...]