Pseudo Classes & Elements

I. What are Pseudo-classes?

They are keywords that we can use in CSS to target elements in a particular state.

For example:

  • :hover - when we hover over an element
  • :focus - when a field is in focus
  • :first-child - when an element is the first child of a parent element

We use pseudo classes by adding them on to the end of our selector.

Syntax:

selector:pseudo-class {
  property: value;
}

II.Pseudo-classes examples

We can display links in different ways:

/* unvisited link */
a:link {
  color: red;
}

/* visited link */
a:visited {
  color: gray;
}

/* mouse over link */
a:hover {
  color: yellow;
  text-decoration: underline;
}

/* selected link */
a:active {
  color: blue;
}

2. :focus Pseudo-class

With :focus Pseudo-class, we can style an element when it’s focused.

For example, we change the border of an input when it’s focused

form input:focus {
  border: 4px dashed gray;
}

3. :valid Pseudo-class

We can also change the style of an input when it’s valid.

For example, when a user typed in a valid email, the border’s color changes to blue

form input:valid {
  border: 4px solid blue;
}

4. :first-child Pseudo-class

The :first-child Pseudo-class can target the child of a parent element when it’s the first child inside the parent element.

<ul>
  <li>Milk</li>
  <li>Butter</li>
  <li>Cheese</li>
</ul>
ul li:first-child {
  border: 2px solid red;
}

III. What are Pseudo-elements?

Pseudo Elements allow us to inject dynamic content or style the content inside an element.

Syntax

The syntax of pseudo-elements:

selector::pseudo-element {
  property: value;
}

List of Pseudo Elements:

  • ::after
  • ::before
  • ::first-letter
  • ::first-line
  • ::selection

1. ::first-letter pseudo-element

The ::first-letter can add style to the first letter of a text.

p::first-letter {
  color: red;
  font-size: 30px;
}

2. ::first-line pseudo-element

::first-line adds a special style to the first line of a paragraph.

p::first-line {
  font-weight: bold;
  font-size: 1.2em;
}

3. ::before pseudo-element

::before pseudo-element can insert some content before the content of an element.

p::before {
  content: url(smiley.gif);
}

4. ::after pseudo-element

::after can insert content after the content of an element.

p::after {
  content: "...";
}

5. ::selection pseudo-element

We can change the style of something when it’s selected with ::selection

p::selection {
  background-color: red;
  color: white;
}