CSS Selectors
Pseudo-Element Selectors
Often, we want to add decorations, styles, or additional content to our elements without altering the underlying HTML. This is where pseudo-element selectors come into play, allowing us to create and style fictitious parts of our elements, such as ::before
and ::after
.
What are Pseudo-Elements?
Pseudo-elements are selectors that allow you to style certain parts of HTML elements that do not exist in the DOM tree as separate nodes. They are useful for adding styles or content that does not need to be part of the HTML document but should be visually represented.
Example of ::before
Using ::before
allows you to insert content before an element's content. This is useful for, for example, adding decorative icons or prefixes.
/* Add a heart before each h2 header *//* Applicable HTML: <h2>Title</h2> */h2::before {content: "♥ ";color: red;}
Example of ::after
Similarly, ::after
allows you to insert content after an element's content. This can be useful for adding suffixes or decorations that follow the text.
/* Add a line after paragraphs *//* Applicable HTML: <p>Paragraph text</p> */p::after {content: "";display: block;width: 100%;height: 2px;background-color: black;margin-top: 10px;}
Common Pseudo-Elements
In addition to ::before
and ::after
, there are other pseudo-elements you can explore to apply styles creatively:
::first-letter
: Selects the first letter of a block of text.::first-line
: Selects the first line of a block of text.::selection
: Applies styles to the portion of a document that has been selected by the user.
Other Utilities of Pseudo-Elements
Pseudo-elements are not just for adding content. They can also be used to create unique visual effects, such as shadows or shapes that are part of a larger design without requiring additional elements in the HTML.
Visual Effect Example
Suppose we want to create a shadow effect behind a title to give it more depth.
/* Create a shadow behind an h1 title *//* Applicable HTML: <h1>Main Header</h1> */h1::after {content: "";position: absolute;width: 100%;height: 10px;background-color: grey;z-index: -1;top: 5px;left: 5px;}
Conclusion
Pseudo-elements offer a powerful way to enhance the aesthetics of our web pages without overloading the HTML. They are especially valuable for designers who want to create clean and aesthetically pleasing interfaces.
In the next topic, we will explore how to combine selectors to achieve more specific and powerful element selection.
Support Chuck’s Academy!
Enjoying this course? I put a lot of effort into making programming education free and accessible. If you found this helpful, consider buying me a coffee to support future lessons. Every contribution helps keep this academy running! ☕🚀

Chat with Chuck
