A pseudo-class is used to define a special state of an element. They are CSS selectors with a colon preceding them.

/* Change the background to yellow
when the textarea has focus */
textarea:focus {
  background: yellow;
}

The above CSS only works when the textarea has the cursor focus. We will introduce some common used pseudo-classes here.

Link-related pseudo class selectors

An anchor can have the following states.

/* unvisited link 
 - when a link is not visited 
 - the anchor must have the href attribute */
a:link {
  color: blue;
}

/* hovered link 
 - when a link has been visited before */
a:visited {
  color: red;
}

/* hovered link 
 - when the mouse cursor rolls over a link */
a:hover {
  color: green;
}

/* selected link 
 - when a link is being clicked */
a:active {
  color: black;
}

  Try it yourself!

Input related pseudo-classes

An input or a textarea element can have the following selectors:

/* when the textarea 
 has the cursor focus. */
textarea:focus {
  background-color: yellow;
}

/* when the element is enabled
 and ready to use (the normal state). */
input:enabled  {
  color: green;
}

/* when the element is disabled (has
 the disable attribute). */
input:disabled  {
  color: gray;
}

/* when the checkbox is checked. */
input:checked {
  width: 50px;
  height: 50px;
}

  Try it yourself!

Position/Number-based pseudo class selectors

We could select the elements based on their position or relation with their parents or other elements.

:first-child – Selects the first element within a parent.

:last-child – Selects the last element within a parent.

:nth-child() – Selects elements based on a simple provided algebraic expression (e.g. “2n” or “4n-1”). Has the ability to do things like select even/odd elements, “every third”, “the first five”, and things like that.

:nth-last-child() – Works like :nth-child, but it counts up from the bottom instead of the top.

:nth-of-type() – Works like :nth-child, but used in places where the elements at the same level are of different types.

:nth-last-of-type() – Works like :nth-of-type, but it counts up from the bottom instead of the top.

:first-of-type – Selects the first element of this type within any parent.

:last-of-type – Selects the last element of this type within any parent.

:only-of-type – Selects only if the element is the only one of its kind within the current parent.

July 23rd, 2016|Categories: CSS Selectors, Learn HTML and CSS|Tags: , |

Leave A Comment