CSS Pseudo Elements
📣 Sponsor
CSS gives us a lot of flexibility in style, but very little in creating new elements. However, there is one way we can add new containers of content, and content, with CSS, and that is using pseudo elements. Pseudo elements use the keyword :before
and :after
.
How Pseudo Elements Work
A pseudo element is attached to an already existing HTML element on the page you are targeting. The reason we have :before
and :after
is because we can have content before (but within the element we select) or after.
To bring this to life, let's look at an example. Here we will add some text before and after a div.
<div class="my-container">Name</div>
.my-container:before {
content: 'Hello My ';
color: orange;
}
.my-container:after {
content: ' Is...';
color: pink;
}
How it looks:
Name
Icons
Psuedo elements have one of their main use cases in CSS icons. On Fjolt, we use FontAwesome quite extensively. If we want to add an icon before an anchor, for example, we can easily do that with a pseudo element if we know the icon code, which is given on the FontAwesome icon page:
p:before {
font-weight: 100;
content: '\f058';
margin: 0 0.5rem 0 0;
font-family: 'Font Awesome 5 Pro';
}
I have an icon!
Covers
We aren't limited to inline styles for pseudo elements, though. We can also set a pseudo element to have an absolute position, so it can take up an entire container. This is frequently used to create a 'backdrop' for modals:
#container {
position: relative;
padding: 1rem;
box-sizing: border-box;
overflow: hidden;
height: 235px;
border-radius: 10px;
}
#container:after {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: linear-gradient(45deg, #0037ff, #00adff);
opacity: 0.2;
}
#modal {
background: white;
position: absolute;
left: 20%;
z-index: 10;
border-radius: 10px;
width: 60%;
height: 200px;
box-shadow: 0 2px 20px rgb(0 0 0 / 10%);
padding: 1rem;
box-sizing: border-box;
font-weight: 600;
}
<div id="container">
<div id="modal">
I am a modal!
</div>
</div>
More Tips and Tricks for CSS
- An Interactive Guide to CSS Flex Box
- CSS Transitions
- Multi colored text in CSS
- iOS Crystalline Blurred Backgrounds with CSS Backdrop Filters
- Making a CSS Only Minecraft Chicken
- How to do Deletion Animations with CSS
- Creating a Javascript Drawing and Annotation Application
- CSS States
- How the CSS Box Model Works
- Creating Custom, Interactive CSS Checkboxes