Home / Blog / Insights / Fun with :before and :after pseudo elements
•
Fun with :before and :after pseudo elements
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.
.wrapper {
position: relative;
z-index: 0;
}
.shape {
background-color: orange;
border-radius: 50%;
display: inline-block;
margin-right: 100px;
height: 80px;
width: 80px;
position: relative;
z-index: 0;
}
The result:
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:
.wrapper:before {
content: ' ';
background-color: #ccc;
display: block;
height: 6px;
width: 80px;
position: absolute;
left: 90px;
top: 35px;
z-index: 1;
}
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.
.shape:before {
content: "o o";
font-size: 20px;
position: absolute;
left: 15px;
top: 21px;
z-index: 1;
}
.shape:after {
content: "(";
font-size: 20px;
position: absolute;
left: 26px;
top: 40px;
z-index: 1;
-ms-transform: rotate(-90deg); /* IE 9 */
-webkit-transform: rotate(-90deg); /* Chrome, Safari, Opera */
transform: rotate(-90deg);
}
.shape:first-child:before {
left: 36px;
top: 21px;
}
.shape:first-child:after {
left: 44px;
top: 40px;
}