CSS3 Background Image Cropping

Try Semtex – the new HTML5, CSS3 and JavaScript UI framework!

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>

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 and follow me on Twitter or check my website for more cool stuff! Happy new year!

Relates Posts