Adding presentational text with CSS


While it’s best practice to separate your presentation layer (CSS) from your content (HTML) when building a website, sometimes these lines can be blurred when you want to add some text purely for presentational purposes. This is where the CSS attribute ‘content’ comes in. This attribute can be used to add text to elements, but only works when using the pseudo selectors :before and :after (this isn’t the case in Opera, and works on anything). The content attribute is supported in all modern browsers, including IE8+. Below are some different ways the content attribute can be used.

Appending content to labels

This attribute can be really handy when you’re working with a framework or library, and something is hard coded that you would like to add to. I’ve come across the problem with a lot of modules/plugins for CMS’s like Drupal and WordPress.

Below is some example CSS for adding a colon ‘:’ after form labels:

label:after {
    content: ':';
}

It’s that simple, and saves a lot of time digging around trying to hard code it.

Adding symbols to elements

Frequently I’ve wanted to add symbols to elements like links or buttons, for example, adding ‘»’ to the end of links.

The content attribute doesn’t allow HTML, so to add symbols to content, you will need to add the HEX value for that symbol instead. A good list of HTML characters and their HEX values can be found here (http://www.ascii.cl/htmlcodes.htm). So to add ‘ »’ to the end of links, your CSS would look like this:

a:after {
    content: ' BB';
}

The ‘’ indicates that the following value is in HEX.

Separating inline links

Sometimes when I have a list of inline links, I want to use some text as a separator or list bullet. If your list is inline, to add an end dash between list items your CSS would look something like this:

ul li:before {
    content: ' 2013 ';
}

ul li:first-child:before {
    content: '';
}

Clearing floats

Another great use of the content attribute is to clear floats with it. The following CSS, when applied to a container with floated child elements, will cause the container to be the full height of its children, instead of shorter.

.clear-floats:after {
    content: ".";
    clear: both;
    display: block;
    visibility: hidden;
    height: 0;
}

As you can see, adding text with CSS sometimes can be quite useful, as long as you maintain the separation between content and presentation.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top