CSS Combinators:
In CSS, combinators are used to define relationships between different HTML elements. They allow you to select elements based on their relationships to other elements in the document structure.
There are several types of CSS combinators:
1. Descendant Selector (Whitespace):
- Selects all elements that are descendants of a specified element.
css
div p {
/* Selects all <p> elements that are descendants of a <div> */
}
2. Child Selector (`>`):
- Selects all direct children of a specified element.
css
div > p {
/* Selects all <p> elements that are direct children of a <div> */
}
3. Adjacent Sibling Selector (`+`):
- Selects an element that is immediately preceded by a specified element.
css
h2 + p {
/* Selects the <p> element that is immediately preceded by an <h2> */
}
CSS Combinators |
4. General Sibling Selector (`~`):
- Selects all siblings that are at the same level and have the same parent as a specified element.
css
h2 ~ p {
/* Selects all <p> elements that are siblings of an <h2> and share the same parent */
}
5. Universal Selector (`*`):
- Selects all elements, regardless of type.
css
* {
/* Selects all elements in the document */
}
6. Grouping Selector:
- Groups multiple selectors together to apply the same styles to different elements.
css
h1, h2, h3 {
/* Applies styles to <h1>, <h2>, and <h3> elements */
}
These combinators provide flexibility in styling and selecting elements based on their relationships within the HTML document. When combined with other CSS selectors and properties, they offer powerful ways to target specific elements or groups of elements for styling.