Psuedo Elements

Psuedo Elements

Introduction

  • Pseudo-elements in CSS allow you to style specific parts of an element, or generate content before or after an element's actual content.

  • Pseudo-elements are denoted by double colons :: or :and they come in various types.

  • Psuedo Elements like after and before should be used when we dont want to add the element to the DOM

  • These elements will get placed in the content section of another element

  • Psuedo Elements like after and before cannot be applied to image tag

1. ::before and ::after:

These pseudo-elements are used to insert content before and after the content of an element, respectively.

.element::before {
  content: "Before ";
}

.element::after {
  content: " After";
}

2. ::first-line and ::first-letter:

::first-line selects the first line of a block, and ::first-letter selects the first letter of the first line.

p::first-line {
  font-weight: bold;
}

p::first-letter {
  font-size: 150%;
}

3. ::selection:

Used to style the portion of an element that is selected by the user.

::selection {
  background-color: yellow;
  color: black;
}

4. ::placeholder:

Targets the placeholder text in input elements.

input::placeholder {
  color: #999;
}

5. ::before and ::after for Creating Decorative Elements:

These are often used to create decorative elements, such as overlays, as demonstrated in the previous examples.

.container::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1;
}

6. ::nth-child and ::nth-of-type:

Selects elements based on their position in a parent element.

ul li:nth-child(odd) {
  background-color: #f0f0f0;
}

ul li:nth-of-type(3n) {
  color: red;
}

7. ::before and ::after for Clearing Floats:

Used for clearfix techniques to clear floated elements.

.clearfix::before,
.clearfix::after {
  content: "";
  display: table;
  clear: both;
}