Understanding Pseudo-classes and Pseudo-elements in CSS
Published: 2023-07-23 15:21:27

Pseudo-classes and pseudo-elements are two fundamental CSS concepts that enable users to target or select specific elements based on various conditions or add special effects to elements without modifying the HTML structure.

In this article, we will explore what pseudo-classes and pseudo-elements are, their differences and how to use them in your CSS code with illustrative examples.

## 1. Pseudo-classes

Pseudo class is a fundamental CSS concept that allows users to target and style an element. The styling could be based on their state or position within the web page. With Pseudo classes, you can select an element that cannot be easily targeted by standard CSS selectors. For example, Pseudo elements can be used to
•	Apply styles when user hovers an element
•	Apply styles to an element while it is being activated 
•	Apply styles to the portion of an element that is selected by the user. They are denoted with single colon (:)


### Syntax:
The syntax to use a pseudo-class is as follows:
```css
selector:pseudo-class {
  /* styles */
}
```

### Examples:

#### 1.1 Hover Pseudo-class
The `:hover` pseudo-class is used to style an element when the user hovers over it with the mouse cursor. The `:hover` pseudo-class is commonly used with a CSS selector to add interactivity and visual effects when a user hovers over the targeted element.

{% codepen https://codepen.io/joanayebola/pen/bGQjevB %}

#### 1.2 Active Pseudo-class
The `:active` pseudo-class is used to style an element when it is being activated or clicked by a user. This pseudo class always you to apply styling to an element while it is being click and reverts to normal after the user releases the click. It is also one of the user interface pseudo classes.

{% codepen https://codepen.io/joanayebola/pen/oNQMLqR %}


#### 1.3 Focus Pseudo-class
The `:focus` pseudo-class is used to style an element when it gains focus, such as when an input field is selected by a user. Unlike the `:active` pseudo class that reverts to normal after the user releases the click, the `:focus` pseudo class applies the styling during the entire period that it retains focus until it loses it


{% codepen https://codepen.io/joanayebola/pen/ZEmjOox %}

###More Types of Pseudo Classes

1. **Link-related pseudo-classes**:
   - `:link`: Styles unvisited links.
   - `:visited`: Styles visited links

2. **User action pseudo-classes**:
   - `:target`: Styles the target element of the current URL's fragment identifier (used with anchor links).

3. **Form-related pseudo-classes**:
   - `:enabled`: Styles form elements that are not disabled.
   - `:disabled`: Styles form elements that are disabled.
   - `:checked`: Styles radio buttons or checkboxes that are checked.
   - `:valid`: Styles form elements with valid input (e.g., for input validation).

4. **Child and sibling pseudo-classes**:
   - `:first-child`: Styles an element that is the first child of its parent.
   - `:last-child`: Styles an element that is the last child of its parent.
   - `:nth-child(n)`: Styles an element that is the nth child of its parent (where n is a number or formula).
   - `:nth-last-child(n)`: Styles an element that is the nth child counting from the end of its parent.
   - `:only-child`: Styles an element that is the only child of its parent.
   - `:first-of-type`: Styles the first occurrence of a specific element type within its parent.
   - `:last-of-type`: Styles the last occurrence of a specific element type within its parent.
   - `:nth-of-type(n)`: Styles the nth occurrence of a specific element type within its parent (where n is a number or formula).
   - `:nth-last-of-type(n)`: Styles the nth occurrence of a specific element type counting from the end of its parent.

5. **UI state pseudo-classes**:
   - `:checked`: Styles elements like checkboxes or radio buttons that are checked.
   - `:indeterminate`: Styles form elements in an indeterminate state (e.g., a checkbox with mixed values).
   - `:default`: Styles the default button in a form.
   - `:valid` and `:invalid`: Styles form elements with valid and invalid input, respectively.

6. **Language-related pseudo-classes**:
   - `:lang(language)`: Styles elements with a specific language attribute (e.g., `:lang(en)` for English).



## 2. Pseudo-elements

### Definition:
A pseudo-element is a keyword that is added to a CSS selector to style a specific part of an element's content without need to add extra HTML elements. Unlike pseudo-classes, which target an element based on its state, pseudo-elements target a part of an element, such as the first line of a paragraph or the last letter of a heading.

### Syntax:
The syntax to use a pseudo-element is as follows:
```css
selector::pseudo-element {
  /* styles */
}
```
Note: In CSS3, pseudo-elements are denoted by two colons (`::`). However, for backward compatibility, using a single colon (`:`) is also supported.

### Examples:

#### 2.1 First-line Pseudo-element
The `::first-line` pseudo-element is used to style the first line of a block-level element, such as a paragraph. It targets the first line of the element, excluding the rest of the content within the element. It can be used for typographic effects or to emphasize the beginning of a paragraph

{% codepen https://codepen.io/joanayebola/pen/yLQqJEp %}

#### 2.2 First-letter Pseudo-element
The `::first-letter` pseudo-element is used to style the first letter of a block-level element. This means that you can apply styles to the initial letter of a paragraph, heading or any other block-level elements

{% codepen https://codepen.io/joanayebola/pen/bGQjejg %}


3. `::before` Pseudo-element:
The `::before` pseudo-element inserts content before the content of the selected element. It can be used to add decorative elements or textual content to an element without modifying the actual HTML content.

**Syntax:**
```css
selector::before {
  /* CSS properties */
  content: "Your content here"; /* This property is mandatory and specifies the content to be inserted */
}
```

**Example:**
Suppose we have a simple HTML element like this:

```html
<div class="example"></div>
```

And we want to add a "✔" symbol before the content of this element using `::before`:

```css
.example::before {
  content: "✔";
  color: green;
  font-size: 18px;
}
```

{% codepen https://codepen.io/joanayebola/pen/jOQpreG %}

4. `::after` Pseudo-element:
The `::after` pseudo-element inserts content after the content of the selected element. It can also be used to add decorative elements or textual content.

**Syntax:**
```css
selector::after {
  /* CSS properties */
  content: "Your content here"; /* This property is mandatory and specifies the content to be inserted */
}
```

**Example:**
Let's add a "📌" emoji after the content of the same HTML element using `::after`:

```css
.example::after {
  content: "📌";
  font-size: 20px;
  margin-left: 5px;
}
```

{% codepen https://codepen.io/joanayebola/pen/XWyBKxP %}

In this example, the "✔" symbol will appear before the content of the `.example` element, and the "📌" emoji will appear after it.

Keep in mind that for both `::before` and `::after` pseudo-elements, the `content` property is mandatory, and without it, the pseudo-element won't generate any content.

## Combining Pseudo-classes and Pseudo-elements

You can also combine pseudo-classes and pseudo-elements to create more specific and refined styles. For example:

```css
a:hover::after {
  content: " (Hovered)";
  color: #007bff;
}
```
In this example, the text "(Hovered)" will be added after the link text when the user hovers over the link.

{% codepen https://codepen.io/joanayebola/pen/bGQjexq %}
###Differences between `Pseudo-classes` and `Pseudo-elements`
pseudo-classes and pseudo-elements provide useful tools for CSS styling, and understanding their differences helps in utilizing them effectively to create dynamic and visually appealing web pages.

|        **Pseudo-Classes**       |         **Pseudo-Elements**         |
|--------------------------------|------------------------------------|
| Target elements based on states or positions within the document tree. | Target specific parts of an element's content without adding extra HTML markup. |
| Denoted with a single colon (:) in CSS. | Denoted with double colons (::) in CSS3 (some older browsers also support single colon notation). |
| Used to style elements based on user interactions or element states. | Used to style specific parts of an element's content or create decorative elements. |
| Examples: :hover, :active, :focus, :visited, :nth-child(n), :first-child, :last-child, etc. | Examples: ::before, ::after, ::first-line, ::first-letter, ::selection, ::marker, etc. |
| Apply styles to elements themselves based on their current state or position. | Apply styles to specific parts of an element's content, like the first letter or first line of text. |
| Often used for dynamic styling and interactivity. | Primarily used for adding decorative content or enhancing the appearance of elements. |
| Pseudo-classes help style elements based on their interaction with users or their positions within the document structure. | Pseudo-elements help style specific parts of an element's content to create unique visual effects or improve design aesthetics. |
| They usually target entire elements and their styles can affect the element's entire appearance. | They target specific parts of an element's content, allowing you to apply different styles to those parts. |
|  |





## Conclusion

Pseudo-classes and pseudo-elements are valuable tools in CSS for targeting specific elements based on various states or parts of an element. They enhance the user experience by providing interactive and visually appealing effects. By understanding and utilizing these features effectively, you can create more dynamic and engaging web designs.

Remember that browser support might vary for some pseudo-elements and pseudo-classes, so always check the compatibility before implementing them in a production environment.

Connect with me on <a href="https://twitter.com/codesbyjojo?t=aDRu6iFCVppmQoLHNSV9Xw&s=09">twitter</a>