CSS combination selectors
CSS Combination Selector
CSS Combination Selector
The combination selector illustrates the direct relationship between two selectors.
CSS combination selectors include various combinations of simple selectors.
There are four combination methods in CSS3:
Descendant selector (separated by spaces)
Child element selector (separated by greater than sign)
Adjacent sibling selectors (separated by plus signs)
Plain sibling selectors (separated by dashes)
Descendant selectors
Descendant selectors match all worthy elements descendant elements.
The following example selects all <p> elements and inserts them into the <div> element:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> div p { background-color:#00ff00; } </style> </head> <body> <div> <p>朝辭白帝彩云間</p> <p>千里江陵一日還</p> </div> <p>兩岸猿聲啼不住</p> <p>輕舟已過萬重山</p> </body> </html>
Child element selector
Compared with descendant selectors, child elements Selectors (Child selectors) can only select elements that are children of an element.
The following example selects all direct child elements<p> in the <div> element:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> div>p { background-color:blue; } </style> </head> <body> <h1>靜夜思</h1> <div> <h2>床前明月光</h2> <p>疑是地上霜</p> </div> <div> <span><p>舉頭望明月</p></span> <p>低頭思故鄉(xiāng)</p> </div> </body> </html>
Adjacent sibling selector
Adjacent sibling selector (Adjacent sibling selector) can select an element immediately following another element, and both have the same parent element.
If you need to select an element immediately after another element, and both have the same parent element, you can use the Adjacent sibling selector.
The following example selects all the first <p> elements after the <div> element:
<html> <head> <meta charset="utf-8"> <style> div+p+p { background-color:yellow; } div+p { background-color:red; } </style> </head> <body> <h1>清明</h1> <div> <h2>清明時節(jié)雨紛紛</h2> <p>路上行人欲斷魂</p> </div> <p>借問酒家何處有</p> <p>牧童遙指杏花村</p> </body> </html>
Normal adjacent sibling selector
Normal sibling selection The selector selects all adjacent sibling elements of the specified element.
The following example selects all adjacent sibling elements <p> of all <div> elements:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> div~p { background-color:yellow; } </style> </head> <body> <div> <p>畫</p> </div> <div> <p>遠(yuǎn)看山有色</p> <p>近聽水無聲</p> </div> <p>春去花還在</p> <p>人來鳥不驚</p> </body> </html>
Adjacent refers to the next one, and it has nothing to do with the previous one.