How to replace and add HTML text elements with CSS

- by

CSS-LogoIn some circumstances you may can replace HTML text elements via CSS. This is useful if you don’t have access to the source files, or if you want to override text in a Child Theme’s stylesheet.

There are several approaches to this conundrum, I’ll show you two of them. Both require that you have a class, ID or element that you can target. You then either amend more text to it, or replace the existing text completely via the CSS pseudo-elements before and after.

This isn’t always successful though as the original styling may not survive the surgery. Let’s take a look.

Option 1: The Visibility Hack

Here’s the easiest way to replace something. In this example I’ll target a class called myelement:

.myelement {
	visibility: hidden;
}

.myelement:before {
	content: 'This is new content, replacing existing content';
	visibility:visible;
}

What’s happening here? First we grab hold of our element and set its visibility to hidden, making it vanish. Next we’ll add our own content before the original, thereby replacing it, and make it visible again.

Instead of “visibility” you can also try “display: none” and “display: block”.

If I had wanted to leave the original words and add something else at the end, I can do this:

.myelement:after {
	content: '. Bring it on!';
}

Or if you’d like to insert something before the original I can use this:

.myelement:before {
	content: 'Check this out: ';
}

The original styling will stay intact, however elements that follow the text (for example hyperlinks) may be destroyed when you replace text. Be as specific as possible when targeting text elements.

Option 2: The Out-Of-Vision Hack

A very creative approach is to avoid changing the visibility of existing text by moving it our of vision and then bringing it back. Sometimes changing attributes such as “visibility” or “display” can cause trouble when we try to restore them.

Here we’re doing just that:

.myelement {
	text-indent: -9999px;
	line-height:0;
}

.myelement:after {
	text-indent:0;
	content:'Welcome Back!';
	display:block;
	line-height: initial;
}

This will completely remove my original text and replace it with “Welcome back!”, hopefully in the same styling as before (but then, it may not survive either).

CSS isn’t really made for this, but it’s powerful enough and works in many cases. Try it out!



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

10 thoughts on “How to replace and add HTML text elements with CSS”

  1. Or if you’d like to insert something before the original I can use this:

    .myelement:after {
    content: ‘Check this out: ‘;
    }

    Should be:

    myelement:before {
    content: ‘Check this out: ‘;
    }

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.