2012年4月30日 星期一

Goodbye -9999px: A New CSS Image Replacement Technique

The -9999px image replacement technique has been popular for the best part of a decade. To replace a text element with an image, you use the following code:

  1. <h1>This Text is Replaced</h1>  
  2. <style>  
  3. h1  
  4. {  
  5.     background: url("myimage") 0 0 no-repeat;  
  6.     text-indent: -9999px;  
  7. }  
  8. </style>  
<h1>This Text is Replaced</h1> <style> h1 { background: url("myimage") 0 0 no-repeat; text-indent: -9999px; } </style>

The element’s background is displayed and it’s text is moved off-screen so it doesn’t get in the way. Simple and effective. It was often adopted to show graphical titles — that’s rarely necessary now we have webfonts, but you’ll still find it used all over the web.

Until now.

A new technique has been discovered by Scott Kellum and promoted at Zeldman.com:

  1. #replace  
  2. {  
  3.     text-indent: 100%;  
  4.     white-space: nowrap;  
  5.     overflow: hidden;  
  6. }  
#replace { text-indent: 100%; white-space: nowrap; overflow: hidden; }

The code indents the text beyond the width of its container but it won’t wrap and the overflow is hidden.

While it’s a little longer and more difficult to remember, performance can be improved because the browser’s no longer drawing a 9,999px box behind the scenes. It will also prevent the weird left-extended outlines you’ll see around links using hidden text.

I haven’t been able to discover any downsides — only than I wish I’d discovered it first. Have you adopted the technique? Have you experienced any issues?

Posted via email from CodeBetter

0 意見: