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>低头思故乡</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>清明时节雨纷纷</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>远看山有色</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.