Css pseudo element/selector :before can be used to prepend some content before an element using a class or any other selector. This can be pretty handy to add common title to an existing block element having same css selector (e.g. class).
:before syntax
Here is :before syntax using css class selector:
.classname:before {
content: "content goes here";
/* other css attributes ... */
}Example – Use :before to add heading to div
Here is an existing html for a block (class=”myclassnopseudo”) which displays some text.
<style>
.myclassnopseudo {
background-color: lightgray;
position: relative;
}
</style>
<div class="myclassnopseudo">
Demo text...
</div>
Now we add :before pseudo element to class myclass. Here is the code and how it renders.
<style>
.myclass {
background-color: lightgray;
position: relative;
}
.myclass { padding-top: 30px;}
.myclass:before {
content:"code";
color: white;
background: green;
width: 100%;
position: absolute;
top: 0;
}
</style>
<div class="myclass">
Demo text...
</div>Few points to note
- Similar to pseudo element :before, we can use :after to add something after the block.
- We had to use padding-top to create some room for the heading.
- The div for which we want to use :before pseudo element should be a positioned element (absolute, relative or fixed).