Earlier we discussed advanced CSS selections. In that, we decided not to bring up pseudo elements, in an attempt to keep the post at a more readable length. A Pseudo element is not written in HTML, but is created and selected purely through the use of CSS. Let's look at some examples and discuss how we can use them using real-world examples.
In the current version of CSS - CSS3 - Pseudo elements are targeted using a double colon after a selector, followed by the name of the pseudo element.
#header::before { /* CSS Rules Go Here */ }
The two main pseudo elements are ::before and ::after. These can be applied to any element that can have children and are most often used to add some sort of aesthetic design element either before or after an element. For example, we could use the ::after pseudo element to add an arrow after all links.
/* Add an arrow after links */ a::after { content: "→"; }
The above code would result in links looking like this:
You can also use ::before in the same way to add something in before an element.
If you're familiar with the float property in CSS, you also are aware of what a clearfix is. In a case where you want to create a clearfix without needing a separate element, you could use the ::after pseudo element to make one. An example is below:
.clearfix::after { display: block; content: ""; clear: both; }
Note that we must define the display type as block, as inline elements cannot hold the clear property. We also must include the content property as pseudo elements do not appear without that property defined.
::before and ::after are by far the most common pseudo elements, but there are others. Let's go through them and learn what they are used for:
These pseudo elements are less common, but definitely used on many sites. A modern trend is to customize the background color of highlighted text, which can simply be done like so:
::selection { background: red; color: white; }
Note that there are other pseudo elements currently in development that should only be used for experimental purposes, not on production code. These will likely be finished at some point in the near future, so this list should not be considered definitive.