How Can We Help?
< All Topics

Pseudo-classes and Combinators

CSS pseudo-classes and combinators provide powerful selectors that allow you to target specific elements based on various conditions and relationships within the document structure. They enable you to apply styles to specific states or positions of elements. Let’s explore CSS pseudo-classes and combinators to enhance your styling capabilities.

Pseudo-classes

Pseudo-classes select elements based on specific states or conditions. They are denoted with a colon (:) followed by the pseudo-class name. Here are some commonly used pseudo-classes:

  • :hover: Applies styles when the element is being hovered over.
  • :active: Applies styles when the element is being activated, such as when it is clicked.
  • :focus: Applies styles when the element has keyboard focus.
  • :nth-child(): Selects elements based on their position in relation to their parent. For example, :nth-child(odd) selects every odd child element.
  • :first-child: Selects the first child element of its parent.
  • :last-child: Selects the last child element of its parent.
a:hover {
  color: red;
}

button:active {
  background-color: green;
}

input:focus {
  border: 1px solid blue;
}

li:nth-child(odd) {
  background-color: lightgray;
}

div:first-child {
  font-weight: bold;
}

p:last-child {
  margin-bottom: 0;
}

Combinators

CSS combinators allow you to select elements based on their relationships to other elements. There are four types of combinators:

  • Descendant selector ( “): Selects elements that are descendants of a specific element.
  • Child selector (>): Selects elements that are direct children of a specific element.
  • Adjacent sibling selector (+): Selects the element immediately following another element.
  • General sibling selector (~): Selects elements that are siblings of a specific element.
div p {
  color: blue;
}

ul > li {
  font-weight: bold;
}

h2 + p {
  margin-top: 0;
}

p ~ span {
  font-style: italic;
}

Conclusion

CSS pseudo-classes and combinators provide powerful selectors that allow you to target specific elements based on various conditions and relationships. By using pseudo-classes like :hover, :active, and :focus, you can apply styles to elements based on user interactions. Combinators like the descendant selector, child selector, adjacent sibling selector, and general sibling selector help you target elements based on their relationship to other elements. Experiment with different pseudo-classes and combinators to enhance your CSS styling capabilities and create dynamic and targeted styles for your web pages.

Table of Contents