CSS Combinators
- Página anterior Alinhamento CSS
- Próxima página Pseudo-classe do CSS
CSS Combinators
Combinators are a mechanism for explaining the relationship between selectors.
CSS selectors can contain multiple simple selectors. We can include a combinator between simple selectors.
There are four different combinators in CSS:
- Descendant Selector (space)
- Child Selector (
>
) - Adjacent Sibling Selector (
+
) - General Sibling Selector (
~
)
Descendant Selector
The descendant selector matches all elements that are descendants of the specified element.
The following example selects all <p> elements within the <div> element:
Instance
div p { background-color: yellow; }
Child Selector
The child selector matches all elements that are child elements of the specified element.
The following example selects all <p> elements that are child elements of the <div> element:
Instance
div > p { background-color: yellow; }
Adjacent Sibling Selector
The adjacent sibling selector matches all elements that are adjacent同级elements of the specified element.
Sibling (同级) elements must have the same parent element. 'Adjacent' means 'immediately following'.
The following example selects all <p> elements that follow the <div> element:
Instance
div + p { background-color: yellow; }
General Sibling Selector
The general sibling selector matches all elements that are同级elements of the specified element.
The following example selects all <p> elements that are同级elements of the <div> element:
Instance
div ~ p { background-color: yellow; }
All CSS Combinator Selectors
Selector | Example | Example Description |
---|---|---|
element element | div p | Select all <p> elements within the <div> element. |
element>element | div > p | Selecione todos os elementos <p> cujo elemento pai é o elemento <div>. |
element+element | div + p | Selecione todos os elementos <p> que seguem imediatamente após o elemento <div>. |
element1~element2 | p ~ ul | Selecione cada elemento <ul> que tenha o elemento <p> como elemento anterior. |
Leitura adicional
Livro extra:Seletor descendente CSS
Livro extra:Seletor de elemento filho CSS
Livro extra:Seletor de irmão adjacente CSS
- Página anterior Alinhamento CSS
- Próxima página Pseudo-classe do CSS