CSS3 Background Image Cropping

HTML5, CSS3 and JavaScript

The Fine Art of Web Development by Martin Ivanov

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:

[sourcecode language=”html”]
<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>
[/sourcecode]

The CSS:

[sourcecode language=”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;
}
[/sourcecode]

The Icons Sprite

icons

And voilà! That’s the result:

css3-background-image-cropping

The Advantages

The Disadvantages

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

Categories and Tags
Links

© 2006 - 2023 Martin Ivanov