English-only | Jenom česky | Bilingual/Dvojjazyčně

CSS Technique: Replacing Text By An Image

Sometimes, we want a decorative text on the web page, but we can't reach it by formatting the text. Therefore we replace the text by an image containing the graphical presentation of the text. However, these pictures have just decorative purpose (they don't carry any information) — from the point of view of the semantics, they aren't welcome in the code. They belong to the stylesheet, not to the page itself. How to do it?

First: Simple Solution

To "move" an image to the CSS isn't difficult thing. We may just set dimensions of the element to the picture's dimensions. Then we define the image to be the element's background image. And finally — to prevent the image to be overlaid by the text — we enclose the text in a neutral element (span) and hide it in the CSS.

   #chapter-one {
      margin:0; padding:0;
      width:200px; height:80px;
      background:url("chapter-one.gif") top left no-repeat;
      }
   #chapter-one span { display:none }
   
...
   
   <h2 id="chapter-one"><span>Chapter One</span></h2>

See the example 1.

There is a disadvantage of this solution. If the image is unreachable or can't be displayed, nothing is visible. The only available text has been hidden. That's why a bit more complicated technique may be better:

Second: More Compatible Method

The idea to assure the element is usable even with unreachable image, is following. The text won't be enclosed in the neutral element span, but it's placed beside it. The span stays empty, but we format it with the background image and absolutely positioned, replacing the original text.

   #chapter-one {
      margin:0; padding:0;
      position:relative;
      width:200px; height:80px;
      overflow:hidden;
      }
   #chapter-one span {
      display:block;
      position:absolute; left:0; top:0; z-index:1;
      width:200px; height:80px;
      margin:0; padding:0;
      background:url("chapter-one.gif") top left no-repeat;
      }

...

   <h2 id="chapter-one">Chapter One<span></span></h2>

The usage is demonstrated in the example 2. The text will be visible, if the image (for any reason) cannot be displayed. Otherwise, the image covers the text. For a case when the text is longer then the image width, the overflow:hidden is used (otherwise the text would "protrude" under the image).

Note: We can format links in similar way. We make the A-element a block and treat it as the title in previous examples. We can also add second image for the hover-state. For details see the example 3. (Of course, we can use the one-image-rollover as well.)