CSS ::before and ::after pseudo elements having been gathering quite a bit of attention lately in the front end developer scene. They have actually been around since CSS 2.1, you might have even seen them used in a utility clearfix class that has been around for years. However more recently we are starting to see some pretty cool stuff done with them for instance pure css GUI icons.
First of all, What is a Pseudo Element?
A Pseudo Element is basically a phoney or ghost element that inserts in this case either before or after an actual real element that we are targeting. It should not be confused with Pseudo Class’s that do not generate content. In the beginning Pseudo Elements used single colons “:” however the spec has been revised and now to differentiate Pseudo Elements from Pseudo Classes, elements now use double colons “::” while classes remain with the single colon.
However most broswers still support the single colon for Pseduo Elements. In fact IE8 will only recognize single colons so if you want the most browser support, use singe colons. For the purpose of this article i will stick with the spec and demonstrate with double colon.
Using ::before and ::after is relatively easy. The only thing to remember is that you must declare the “content” property in order to generate the ::before and ::after elements.
The content property can take:
A string of text or ISO Uniden codes
A Url to an image.
Will return as a string the value of the associated element attribute value. For example some sites will display links href values in the print stylesheets.
- counter() and counters()
Can be used to display any CSS counters you have.
TIP: You can set the content as an empty string if you simply want a box to style.
content:"I'll appear before box";
content:"I'll appear after box";
By default these Pseudo Elements display inline. So to add padding, margin, height, width etc you will need to explicitly define it as a display block.
A real world example
I typically like to use Pseudo Elements in menus. For instance if we had a menu where some of the items had dropdowns we could indicate this by adding a chevron.
For instance, with this html
We could add a chevron (facing down triangle) to the dropdown item using the ::after Pseudo Element like so
border-left: 8px solid transparent;
border-right: 8px solid transparent;
border-top: 8px solid #000;