Pro HTML5 and CSS3 Design Patterns

(avery) #1
CHAPTER 10 ■ STYLING TEXT

Text Replacement with Image


Problem You want to replace text with an image, and you want the text to be read by a screen reader. You also
want the text to be visible when the image is unavailable.


Solution Insert an empty into the block element that contains the text you want to replace with an
image. Assign the image as the span’s background image. Relatively position the block, and
absolutely position the span. This displays the span in front of the block. Size both the block and the
span to fit the image. Because the block and the span are the same size and the span is in front of
the block, the span’s background image covers the text in the block. If the image is unavailable, the
browser renders the span’s background as transparent, and this lets the text show through.
Assign a unique ID to the block containing the text you want to replace, and style it as follows:
position:relative; positions the block so the background image of the can be positioned
on top of the text.


width and height size the block to fit the image.

padding:0; removes padding that could allow text to show through.
overflow:hidden; ensures that long text doesn’t show through, but be aware that if the
image isn’t displayed, long text could be truncated.
Insert an empty <span> into the block, and style it as follows:

position:absolute;, left:0;, and top:0; position the image over the text in the block.

width and height size the <span> to fit the image.

margin:0; removes margins that could allow text to show through.

background-image:url("FILE.EXT") loads the image.

background-repeat:no-repeat ensures that the image doesn’t repeat.

Pattern^


HTML


CSS


<BLOCK id="UNIQUE-ID"> TEXT <span></span></BLOCK>

#UNIQUE-ID { position:relative; padding:0; overflow:hidden;
width:IMAGE_WIDTH;
height:IMAGE_HEIGHT; }
#UNIQUE-ID span { position:absolute; left:0; top:0; margin:0;
width:IMAGE_WIDTH;
height:IMAGE_HEIGHT;
background-image:url("FILE.EXT");
background-repeat:no-repeat; }

Location This pattern applies to any block, float, absolute, or fixed element.


Tip Text replacement works well with links and buttons that use rollover effects.


Related to Text Replacement with canvas and VML, Invisible Text, Screenreader-only; Background (Chapter 6);
Marginal Graphic Dropcap (Chapter 18)

Free download pdf