Replacing Text with Background Images using CSS: A Clean and Efficient Technique

Learn how to replace text content with background images using CSS for visually appealing and efficient web design. This tutorial explains the `.text-hide` approach, demonstrates its implementation with and without CSS preprocessors (Sass, Less), and highlights best practices for maintaining accessibility when hiding text content.



Replacing Text with Background Images using CSS

The `.text-hide` Technique

In CSS, the `.text-hide` class (or mixin, if using a preprocessor like Sass or Less) provides a technique for replacing an element's text content with a background image. This is often used to create visually appealing elements where the text is purely decorative or acts as a placeholder for the background image. This makes it possible to create a visually pleasing design and improve the aesthetics of a webpage.

Implementing `.text-hide`

The `.text-hide` class typically involves these styles:

  • text-indent: Moves the text far enough off-screen to hide it.
  • background-image: Sets the background image.
  • width and height: Defines the dimensions to match the background image.
  • Other styles as needed to properly position and display the background image.

This technique makes the text visually hidden but ensures that it remains in the DOM (Document Object Model) for accessibility reasons such as screen readers.

Example Using a Mixin

If you are using a CSS preprocessor (like Sass or Less), it's common to create this as a mixin which can then be included where needed.

Example Sass Mixin

@mixin text-hide {
  text-indent: 100%;
  white-space: nowrap;
  overflow: hidden;
  background-size: cover;
  /* ... other styles to position the background image ... */
}

This mixin can then be used to style elements, replacing their text with a background image.

Example Usage

.heading {
  @include text-hide;
}