We can style specific parts of an elements such as first-letter, first-line or even insert before/after it. For these purposes CSS Pseudo Elements are used.
NOTE − To separate CSS Pseudo Classes from Pseudo Elements, in CSS3, pseudo elements use double-colon notation.
Syntax
Following is the syntax for using CSS Pseudo elements on an element −
Selector::pseudo-element { css-property: /*value*/; }
Following are all the available CSS Pseudo Elements −
Sr.No | Pseudo Element & Description |
---|---|
1 | after It inserts something after the content of each mentioned element |
2 | before It inserts something before the content of each mentioned element |
3 | first-letter It selects the first letter of each mentioned element |
4 | first-line It selects the first line of each mentioned element |
5 | placeholder It selects the placeholder text in form elements |
6 | selection It selects the portion of an element that is selected by a user |
Let’s see an example of CSS Pseudo Elements −
Example
<!DOCTYPE html> <html> <head> <style> p::first-letter { background-color: black; } p::first-line { background-color: lightgreen; color: white; } span { font-size: 2em; color: #DC3545; } </style> </head> <body> <h2>Computer Networks</h2> <p><span>A</span> system of interconnected computers and computerized peripherals such as printers is called computer network. </p> </body> </html>
Output
Let’s see another example of CSS Pseudo Elements −
Example
<!DOCTYPE html> <html> <head> <style> div:nth-of-type(1) p:nth-child(2)::after { content: " LEGEND!"; background: orange; padding: 5px; } div:nth-of-type(2) p:nth-child(2)::before { content: "Book:"; background-color: lightblue; font-weight: bold; padding: 5px; } </style> </head> <body> <div> <p>Cricketer</p> <p>Sachin Tendulkar:</p> </div> <hr> <div> <p><q>Chase your Dreams</q></p> <p><q>Playing It My Way</q></p> </div> </body> </html>