CSS3 :nth-child()
規定屬於其父元素的第二個子元素的每個 p 的背景色:
p:nth-child(2) { background:#ff0000; }
<!DOCTYPE html>
<html>
<head>
<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 不支持 :nth-child() 選擇器。</p>
</body>
</html>
CSS3 :nth-of-type()
指定每個p元素匹配同類型中的第2個同級兄弟元素的背景色:
p:nth-of-type(2)
{
background:#ff0000;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鳥教程(runoob.com)</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>
總結一下:
p:nth-child(2)
1.這個元素正好是父元素的第二個元素。2.這個值正好是p。那麼選中
p:nth-of-type(2)
在父元素下面直接找第二個p元素
nth-child
的關鍵詞是child,它關心的是所有子元素。它會對所有子元素生效。ele:nth-child
的意義就是選擇父元素下的第n個子元素,如果他是ele類型的,那麼對他生效,如果他不是ele類型的,則不生效。
nth-of-type
的關鍵詞是type,即他關心的是類型。它不會對所有子元素生效,只會對子元素中符合選擇器要求的類型的子元素進行篩選,而忽略非選擇器要求的類型的子元素。ele:nth-of-type(n)
的意義就是選擇父元素下的第n個ele類型的子元素。