The CSS3 content property is extremely valuable for inserting content into the ::before and ::after pseudo elements. As the Mozilla Developer Network states:
The
content
CSS property is used with the::before
and::after
pseudo-elements to generate content in an element.”
The content property enables us to insert generated content. The content can include:
- String value.
- URI for showing an image.
- The value of an attribute for the element.
- Quotes (open-quote and close-quote).
Further, the content property is widely supported by all major browsers.
I think the most valuable of these is being able to insert a string value.
Let’s look at some examples of using the content property along with the ::before
and ::after
pseudo elements.
Clear
Previous to CSS3 in order to clear floats (or to move an element down past any floated elements) we added an extra element to the DOM where needed.
<style>
.clear {
clear: both;
}
</style>
<div class="content">
<div class="pull-left">Float left</div>
<div class="pull-right">Float right</div>
<div class="clear"></div>
</div>
While this still works with CSS1 and CSS2, we can simply apply a class to the .content
element to clear the floats.
Here is the LESS code for clearing the floated elements:
.clear {
&::before,
&::after {
content: ' ';
display: table;
}
&::after {
clear: both;
}
}
And here is the HTML to go along with our LESS code:
<div class="content">
<div class="pull-left">Float left</div>
<div class="pull-right">Float right</div>
</div>
Breadcrumb
Creating a breadcrumb with the content property allows us to use very simple HTML markup, adding the necessary dividers via CSS. Again I am using the LESS precompiler for my CSS.
Here is the template HTML:
<ol class="breadcrumb">
<li><a href="/">Home</a></li>
<li><a href="/foo">Foo</a></li>
<li><a href="/foo/bar">Bar</a></li>
<li>Here</li>
</ol>
ol.breadcrumb {
list-style: none;
&::before,
&::after {
content: ' ';
display: table;
}
&::after {
clear: both;
}
> li {
float: left;
color: #999;
& + li::before {
content: '\003E';
padding: 0 6px;
}
> a {
color: #666;
}
}
}
See the Pen eNwEoj by Brian Love (@blove) on CodePen.
Non-latin Characters
Any non-latin alphabet characters must be encoded.
The encoding is the hexadecimal value with a preceding backward slash, for example: \0020
.
In the example above I used the hexadecimal value of 20 for the greater-than sign. There are some easy ways to figure out the appropriate value:
- Entity Conversion Calculator - enter the ascii decimal value for the character, or type/paste it to get the CSS and JS hexadecimal value.
- Cheat sheet for HTML, CSS and JS entity characters - a quick lookup tool for common character entities.
- Decimal to Hex Converter - convert the ascii decimal value to the hex value.