Pseudo-Classes/Elements
CSS ::before
Adding Content with Before
CSS ::before adds content via content property, enhancing design.
Understanding the CSS ::before Pseudo-Element
The CSS ::before
pseudo-element allows you to insert content before the content of a selected element. This is accomplished through the content
property. It is widely used for adding decorative elements, icons, or any additional content that enhances the user interface without altering the HTML structure.
Basic Usage of ::before
To use ::before
, you need to define it within a CSS rule for a particular element. Here is a simple example where we use it to add a star symbol before a heading.
In this example, a golden star is added before every h1
element. The content
property specifies what is inserted, and other styles, such as color
and font-size
, are used to style the content.
Using ::before for Decorative Purposes
The ::before
pseudo-element is especially useful for adding decorative elements, such as lines or icons, without cluttering the HTML. Below is an example of adding a decorative line before a paragraph.
In this example, a black line is displayed before every paragraph. The content
property is set to an empty string, and the line is created by manipulating the width
, height
, and background-color
properties.
Adding Icons with ::before
Icons can be effectively added using the ::before
pseudo-element, especially when combined with icon fonts such as Font Awesome. Here's an example of adding a Font Awesome icon before a list item.
This example assumes that Font Awesome is included in the project. The content
property uses the Unicode value corresponding to the desired icon, and the font-family
and color
properties ensure the icon is displayed correctly.
Considerations When Using ::before
While ::before
is a powerful tool for enhancing design, it's important to note that it doesn't alter the document's structure, meaning screen readers might not interpret the added content as part of the main content. Always ensure that essential information is included in the HTML itself for accessibility purposes.
Pseudo-Classes/Elements
- :hover
- :focus
- :active
- :nth-child
- :not
- :first-child
- ::before
- ::after
- Previous
- :first-child
- Next
- ::after