How to replace and add HTML text elements with CSS

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!





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.