Your Course Progress

Topics
0 / 0
0.00%
Practice Tests
0 / 0
0.00%
Tests
0 / 0
0.00%
Assignments
0 / 0
0.00%
Content
0 / 0
0.00%
% Completed

CSS Combinators

CSS combinators are used to select specific elements within the HTML structure, allowing for more precise targeting of styles. They are an important part of CSS selectors, which define the elements that CSS rules will apply to.

The descendant selector selects all elements that are descendants of a specific parent element. It uses a space character to separate the parent and child elements.

p span { /* Styles all <span> elements within <p> elements */
  color: blue;
}
Do You Know?

The descendant selector will select any element that is a descendant of the parent element, including nested elements.

The child selector selects only the direct children of a specific parent element. It uses the greater than sign (>) to separate the parent and child elements.

div > p { /* Styles only <p> elements that are direct children of <div> elements */
  font-weight: bold;
}
Important Note

The child selector will not select elements that are nested within other elements.

The adjacent sibling selector selects the first element that directly follows another element. It uses the plus sign (+) to separate the two elements.

h2 + p { /* Styles only the <p> element that directly follows an <h2> element */
  background-color: lightgray;
}

The general sibling selector selects all elements that follow a specific element, regardless of their direct relationship. It uses the tilde (~) to separate the two elements.

h1 ~ p { /* Styles all <p> elements that follow an <h1> element */
  font-style: italic;
}
Avoid This

Overusing sibling selectors can lead to complex and less readable code.

Summary

  • CSS combinators provide precise control over element selection.
  • Descendant selectors target all descendants of a parent element.
  • Child selectors target only direct children of a parent element.
  • Adjacent sibling selectors target the first element that directly follows another element.
  • General sibling selectors target all elements that follow a specific element.

Discussion