CSS

Last Updated: 10/5/2022

Pseudo-classes

A pseudo-class is used to define a special state of an element.

Syntax

selector:pseudo-class {
  property: value;
}

Anchor Pseudo-classes

  • a:link - unvisited link
  • a:visited - visited link
  • a:active - active link
  • a:hover - mouseover
  • a:focus - element that has focus
  • a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective.
  • a:active MUST come after a:hover in the CSS definition in order to be effective.

Child Elements

  • :first-child - Select the first child of its parent

  • :first-of-type - Select all the first element of its type

  • :nth-child(n) - Selects the nth child of its parent

  • :nth-of-type(n)- Select all the nth element of its type

  • :last-child - Selects the last child of its parent

  • :last-of-type - Select all the last element of its type

  • :nth-last-child(n) - Selects the nth child counting from the last child

  • :nth-last-of-type(n)- Select all the nth element of its type counting from the last child

  • :empty - Selects every element that has no children

  • :not(selector) - Selects every child element that is not the specified element

Select the first child of body element and set the text color

:first-child {
	color: red;
}

Select the first child of the body element and if it is a paragraph apply the styles

p:first-child {
	color: red;
}

Select the first child of section1 element and apply the styles

#section1 :first-child {
}

:nth-child(n)

  • Matches every element that is the nth child of its parent.
  • n can be a number, a keyword (odd or even), or a formula (like an + b).
  • In formula - n starts from 0,1,2...
  • Child index starts from 1,2,3....
div:nth-child(1){
}
div:nth-child(odd){
}
div:nth-child(even){
}
div:nth-child(3n+1){
}

Form control state

  • :checked - Selects every checked element
  • :disabled - Selects every disabled element
  • :enabled - Selects every enabled element
  • :read-only - Selects elements with a "readonly" attribute specified
  • :read-write - Selects elements with no "readonly" attribute
  • :required - Selects elements with a "required" attribute specified
  • :optional - Selects elements with no "required" attribute
  • :valid - Selects all elements with a valid value
  • :invalid - Selects all elements with an invalid value
  • :in-range - Selects elements with a value within a specified range
  • :out-of-range - Selects elements with a value outside a specified range