nth用法:1、“:nth-child(n)”匹配第n個子元素;2、“:nth-last-child(n)”倒數(shù)匹配第n個子元素;3、“:nth-of-type(n)”匹配同類第n個子元素;4、“:nth-last-of-type(n)”。
本教程操作環(huán)境:windows10系統(tǒng)、CSS3&&HTML5版本、Dell G3電腦。
css中nth的用法是什么
1、:nth-child(n)
:nth-child(n) 選擇器匹配父元素中的第 n 個子元素,元素類型沒有限制。
n 可以是一個數(shù)字,一個關(guān)鍵字,或者一個公式。
示例如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>123</title> <style> p:nth-child(2) { background:#ff0000; } </style> </head> <body> <h1>這是一個標題</h1> <p>這是第一個段落。</p> <p>這是第二個段落。</p> <p>這是第三個段落。</p> <p>這是第四個段落。</p> <p><b>注意:</b> Internet Explorer 8 以及更早版本的瀏覽器不支持 :nth-child()選擇器.</p> </body> </html>
輸出結(jié)果:
2、:nth-last-child(n)
:nth-last-child(n) 選擇器匹配屬于其元素的第 N 個子元素的每個元素,不論元素的類型,從最后一個子元素開始計數(shù)。
n可以是一個數(shù)字,一個關(guān)鍵字,或者一個公式。
示例如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>123</title> <style> p:nth-last-child(2) { background:#ff0000; } </style> </head> <body> <p>The first paragraph.</p> <p>The second paragraph.</p> <p>The third paragraph.</p> <p>The fourth paragraph.</p> <p><b>注意:</b> Internet Explorer 8 以及更早版本的瀏覽器不支持:nth-last-child()選擇器.</p> </body> </html>
輸出結(jié)果:
3、:nth-of-type(n)
:nth-of-type(n)選擇器匹配同類型中的第n個同級兄弟元素。
n可以是一個數(shù)字,一個關(guān)鍵字,或者一個公式。
示例如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>123</title> <style> p:nth-of-type(2) { background:#ff0000; } </style> </head> <body> <h1>This is a heading</h1> <p>The first paragraph.</p> <p>The second paragraph.</p> <p>The third paragraph.</p> <p>The fourth paragraph.</p> </body> </html>
輸出結(jié)果:
4、:nth-last-of-type(n)
:nth-last-of-type(n)選擇器匹配同類型中的倒數(shù)第n個同級兄弟元素。
n 可以是一個數(shù)字,一個關(guān)鍵字,或者一個公式。
示例如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>123</title> <style> p:nth-last-of-type(2) { background:#ff0000; } </style> </head> <body> <h1>This is a heading</h1> <p>The first paragraph.</p> <p>The second paragraph.</p> <p>The third paragraph.</p> <p>The fourth paragraph.</p> <p><b>注意:</b> Internet Explorer 8以及更早版本的瀏覽器不支持:nth-last-of-type() 選擇器.</p> </body> </html>
輸出結(jié)果:
(學習視頻分享:css視頻教程)