Entity view (Content)

Modern Approach To CSS Image Replacement

By jharvey
Sep. 15, 2014

Since 2003, front-end developers have come up with different techniques for replacing text with images.

The objective was to be able to display, for example, a title with a special font that differs from the default ones used in browsers, all by conserving the semantic HTML. An image of the text needed to be created with the desired font. It was then displayed as a background image and hid the HTML text. Thus, the desired look was achieved and kept the accessibility to the text in the webpage.

 

Here is a CSS example from early 2000’s:

       .show-image {
width: 40px;
height: 40px;
background: url(../images/my-title-image.png);
}

.hide-text {
text-indent: -9999px;
}

<h1 class="hide-text show-image">Hide this text please!</h1>

 

However, the problem with this method is that the browser is required to render a large box off-screen which can cause a performance hit resulting in an animation bug on iPad1.

Fortunately in 2012, Scott Kellum of VOX Media came out with a new, innovative approach to getting rid of the -9999px “shift-offscreen” CSS hack!  

 

Here is the solution:

       .show-image {
width: 40px;
height: 40px;
background: url(../images/my-title-image.png);
}

.hide-text {
text-indent: 100%; [ get out of the window ]
white-space: nowrap; [ don't come back in ]
overflow: hidden; [ no really, don't come back in ]
}

<h1 class="hide-text show-image">Hide this text better!</h1>

 

So, what are the benefits?

Firstly, we are no longer rendering an enormous 9999px box that never gets used anyway; This results in a dramatic performance improvement with less elements being added to the page. We also optimized our CSS while improving the mobile experience, especially on older devices.

So from now on, I don’t want to see your 9999px text indents, and you can approach your text replacements with class!

 

For further reading, follow up with these related links:

css image replacement museum

zeldman.com

css architectures

Post Tags: