Combinators
A combinator is something that explains the relationship between the selectors. 一个CSS组合器其实是来解释选择器之间关系的。
一个CSS选择器可以包含不止一个 simple selector (简单选择器),在简单选择器之间,我们可以兼一个组合器。
There are four different combinators in CSS3:
- descendant selector 后代选择器
- child selector 孩子选择器
- adjacent sibling selector 相邻兄弟选择器
- general sibling selector 一般同级选择器
Descendant Selector
The descendant selector matches all element that are descendants of a specified element.
匹配指定元素下所有符合条件的元素,而不论元素被嵌套了多少层。即两个元素之间的层次间隔可以是无限的。
如下例,选择<div>元素中所有<p>元素。
div p
{
background-color:yellow;
}
Child Selector
The child selector selects all elements that are the immediate children of a specified element.
匹配某元素下最直接的符合条件的孩子元素(可以是多个),但如果有其他元素包裹住这些元素,则视为不匹配。
div > p
{
background-color:yellow;
}
如下例,会把第一个 h1 下面的两个 strong 元素变为红色,但是第二个 h1 中的 strong 不受影响
<style>
h1 > strong {color: red;}
</style>
<h1>This is <strong>very</strong> <strong>very</strong> important.</h1>
<h1>This is <em>really <strong>very</strong></em> important.</h1>
Adjacent Sibling Selector
sibling是同胞的意思。
The adjacent sibling selector selects all elements that are the adjacent siblings of a specified element.
Sibling elements must have the same parent element, and "adjacent" means "immediately following".
同胞元素必须有相同的父元素,且必须是立刻相跟着的, 再后面的元素则不匹配。比如 大哥+二哥,意思是选则二哥。三哥、四哥,等等则不算在内。
div + p
{
background-color:yellow;
}
General Sibling Selector
The general sibling selector selects all elements that are siblings of a specified element.
选择所有与指定元素同级的元素。
div ~ p
{
background-color:yellow;
}