Replacing Text With Images in CSS

Sometimes we want to decorate our site with nice looking text but can’t achieve it by just formatting the text to a different font. Why not? Because not all users have the same fonts installed in their systems.

With CSS we can replace a piece of text with an image containing the graphical presentation of the text. These images will only serve the purpose of decorating the page with a fancier font because they don’t carry any value to the content of the page.

How Can We Achieve That?

There are some CSS techniques in which you set the dimensions of the element to the image’s dimensions and define the image to be the element’s background image. Also, to prevent the text from overlaying the image we have to enclose this text in a span tag and hide it in the CSS using display: none;

There is a problem with this technique: If the image cannot be displayed (broken link, corrupted file, etc) nothing will be visible to the user because the only available text is hidden. This is a no-no in today’s accessibility standards!

There’s a very simple way to replace your text with an image file. We will still use our image and text, but this time we are going to place an empty span tag next to the text that we are going to hide. Then we are going to position that image absolutely, causing the image to overlay the text. Let’s get to it!

The Image:

Chapter 1 Sample Image

The CSS Code:


h2{
	margin-bottom: 40px;
        font-size: 14px;
}

h2 #chapter1{
	position: absolute;
	width: 240px;
	height: 46px;
	background: url(chapter_1.jpg) no-repeat;
        display: block;
        margin: 0;
        padding: 0;
}

The XHTML Code:


<h2><span id="chapter1"></span>Chapter 1</h2>
  • Note that I added 40 pixels of bottom margin to the h2 element in order to push the paragraph down causing it to clear the image. You can experience with this value depending on the height of your image.

Summary:

With this technique the text will always display even if the image doesn’t load. Also, screen readers will ignore the image and read the piece of text under it – this helps your site’s accessibility. Lastly, this is search engine friendly! Images have no value to search engines but because you have text below them, search engines can read that text. This is a technique that I use abundantly throughout my site.

You can also use this technique with links and also add different images for a rollover state!

Back to top ↑

Leave a comment

Name: (Required)

E-mail: (Required)

Website:

Comment:

Spam protection:
What is the sum of 2 + 7 ?