HTML&CSS基礎-子元素的偽類選擇器
作者:尹正傑
版權聲明:原創作品,謝絕轉載!否則將追究法律責任。
一.html的源代碼
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>子元素的偽類選擇器</title> <style> /** * * 子元素的偽類裝飾器: * :first-child * 可以選中第一個子元素 * :last-child * 可以選中最后一個子元素 * :nth-child(num) * 可以選中任意位置的子元素; * 如果不寫num的值則默認為1,效果和":first-child"偽類相同了; * 如果num的值為"even",則表示偶數位置子元素 * 如果num的值為"odd",則表示奇數位置子元素 * * 可選擇類型: * :first-of-type * :last-of-type * :nth-of-type * 以上元素和":first-child",":last-child",":nth-child(num)"這些非常類似; * 只不過first-child",":last-child",":nth-child(num)"是在所有的子元素中排列。 * 而":first-of-type",":last-of-type",":nth-of-type"是在當前類型的子元素中排列 * */ /** * 案例一: * 為第一個p標簽(該標簽必須是第一個標簽)設置一個背景顏色為黃色 */ p:first-child{ background-color: yellow; } /** * 案例二: * 為最后一個p標簽(該標簽必須是最后一個標簽)設置背景顏色為棕色 */ p:last-child{ background-color: brown; } /** * 案例三: * 選擇第三個位置的子元素將其背景設置為洋紅色 */ p:nth-child(3){ background-color: magenta; } /** * 案例四: * 選擇所有子元素的第一個p標簽並將其背景顏色設置為紅色 */ p:first-of-type{ background-color: red; } /** * 案例五: * 選擇所有子元素的最后一個p標簽並將其背景顏色設置為藍色 */ p:last-of-type{ background-color: blue; } </style> </head> <body> <p>我是一個p標簽</p> <p>我是一個p標簽</p> <p>我是一個p標簽</p> <p>我是一個p標簽</p> <div> <p>我是第一個div的一個p標簽</p> <p>我是第一個div的一個p標簽</p> <p>我是第一個div的一個p標簽</p> <p>我是第一個div的一個p標簽</p> <span>我是第一個div的span標簽</span> </div> <p>我是一個p標簽</p> <p>我是一個p標簽</p> <p>我是一個p標簽</p> <div> <span>我是第二個div的span標簽</span> <p>我是第二個div的一個p標簽</p> <p>我是第二個div的一個p標簽</p> <p>我是第二個div的一個p標簽</p> <p>我是第二個div的一個p標簽</p> <p>我是第二個div的一個p標簽</p> </div> <p>我是一個p標簽</p> <p>我是一個p標簽</p> <span>我是body的span標簽</span> </body> </html>
二.瀏覽器打開以上代碼渲染結果