September 4, 2014
For a recent client project I had to create an HTML/CSS template that would display a branched account linking structure.
Instead of using background images, or resorting to extraneous empty divs to create the linking branches, I used the :before and :after pseudo elements.
The :before and :after pseudo elements create ghost-like or virtual elements elements that are visible on the page, but don’t show up in the DOM. Depending on which of these two pseudo elements you choose, the content gets inserted before or after the content of the selected element. Common usages of these pseudo elements include clearing floats, custom list icons, and text flourishes.
Let’s create two circles and connect them with help from the :before and :after pseudo elements.
Here is our mark-up:
Pretty straightforward. A wrapper element containing our two shapes. Let’s use CSS to make the two shapes into circles and put some space between them.
Time to insert the pseudo element to connect the two circles. We will insert it at the beginning of the content of the wrapper element. Here is the CSS:
content: ' ';
Voila, we now have a link between our two circles:
The content property of the pseudo element accepts a number of different property values, one of which is a string value. We don’t need any text to display inside our pseudo element so we will leave the content property empty. Pseudo elements are inline elements by default, so we changed it to display: block to define a width and height. We applied a background color so we can see it, and then positioned it absolutely relative to it’s parent element wrapper.
Add the CSS below to have a bit more fun with :before and :after pseudo elements, and read this article to see some them being used for all sorts of cool possibilities.
content: "o o";
-ms-transform: rotate(-90deg); /* IE 9 */
-webkit-transform: rotate(-90deg); /* Chrome, Safari, Opera */