1 <!DOCTYPE HTML>2 <HTML>3 <Head>4 <MetaCharSet= "Utf-8" />5 <title>HTML5 Template</title>6 <style>7 em{Color:Gray;}8 Article P em{Color:Green;} 9 aside P em{Color:Orange;}Ten </style> One </Head> A <Body> - <P>This text is very important!</P> - <article> the <H1>Contextual selector is<em>Very</em>Selective</H1> - <P>This example shows how to target a<em>Specific</em>Tag.</P> - </article> - <aside> + <P>Contextual selectors is<em>Very</em>useful!</P> - </aside> + </Body> A </HTML>
1. Context selector: Select an element based on an ancestor or sibling element.
Label 1 label 2 {declaration}
Where label 2 is the target we want to select, and is selected only if label 1 is its ancestor element.
The context selector, strictly speaking, is called the descendant combo selector, which is a set of space-delimited label names. Used to select the label as the descendant of the specified ancestor element. As long as there is a tag in its hierarchy "upstream" there is such an ancestor, then the label will be selected. No matter how many levels are separated from the tag to the context as an ancestor.
The above example shows that the EM element is selected based on the ancestor elements, so that the EM in different labels is rendered in a different state.
Special Context Selectors:
1.1. Sub-selector >
Label 1 > Label 2
Label 2 must be a child element of label 1. Unlike other general context selectors, label 1 in this selector cannot make other ancestor elements outside of the parent element of label 2
1.2, adjacent to the sibling selector +
Label 1 + label 2
Label 2 must be immediately behind its fellow label 1
1.3, General sibling selector ~
Label 1 ~ Label 2
Label 2 must be in (not necessarily next to) its fellow label 1 behind
1.4. Universal Selector *
* (often referred to as the asterisk selector) is a wildcard that matches any element
* {Color:green;}
Causes all elements (text and borders) to turn green.
1 <!DOCTYPE HTML>2 <HTML>3 <Head>4 <MetaCharSet= "Utf-8" />5 <title>HTML5 Template</title>6 <style>7 Section > H2{Color:Red;Font-style:Italic;}/*> sub-selectors*/8 H2 + P{font-variant:Small-caps;}/*+ Immediate Sibling selector*/9 H2 ~ a{Color:Brown;}/*~ General Sibling Selector*/Ten section * a{Color:Red;}/*non-child selectors, applicable to non-child elements a of section*/ One </style> A </Head> - <Body> - < Section> the <H2>An H2 Heading</H2> - <P>This is paragraph 1</P> - <P>Paragraph 2 has<ahref="#">A link</a>In it.</P> - <ahref="#">Link</a> + </ Section> - </Body> + </HTML>
css-Context Selector