:first-child (匹配父元素的第一個子元素)
:first-of-type (匹配父元素的相同子元素的第一個子元素)
這裏還要區分是元素選擇器還是非元素選擇器
下面假設用來舉例的元素是p,類名爲pclass
例如 :
1、:first-child
p:first-child 匹配p標籤的父元素的第一個子元素並且這個子元素必須爲p標籤
.pclass:first-child 匹配類爲pclass的p標籤的父元素的第一個子元素並且這個子元素必須類爲pclass的p標籤
first-child匹配上的情況
1)p:first-child p元素是父元素的第一個子元素
2).pclass:first-child 類爲pclass的p元素是父元素的第一個子元素
first-child 匹配不上的情況
1)、父元素第一個子元素不是p標籤
<style>
p:first-child
{
background:#ff0000;
}
</style>
</head>
<body>
<h1>這是一個標題</h1>
<p>這是第一個段落。</p>
<p>這是第二個段落。</p>
</body>
運行結果
2)、父元素的第一個子元素類不爲pclass
<style>
.pclass:first-child
{
background:#ff0000;
}
</style>
</head>
<body>
<p>這是第一個段落。</p>
<p class="pclass">這是第二個段落。</p>
</body>
運行結果:
2、:first-of-type
p:first-of-type匹配父元素的子元素中的第一個p元素(不管這個p是不是父元素的第一個子元素)
.pclass:first-of-type匹配父元素的子元素中的第一個類爲pclass的元素(可以匹配多個,如果有多個類爲pclass的不同標籤的子元素)
:first-of-type匹配上的情況:
1)pclass對應的p元素是父元素的第一個p元素
<style>
.pclass:first-of-type
{
background:#ff0000;
}
</style>
</head>
<body>
<h1>這是一個標題</h1>
<p class="pclass">這是第一個段落。</p>
<p>這是第二個段落。</p>
</body>
運行結果:
2)匹配所有類爲pclass的不同元素的第一個元素
<style>
.pclass:first-of-type
{
background:#ff0000;
}
</style>
</head>
<body>
<h1 class="pclass">這是一個標題</h1>
<p class="pclass">這是第一個段落。</p>
<p>這是第二個段落。</p>
</body>
運行結果:
:first-of-type匹配不上的情況
1)pclass對應的p元素不是父元素的第一個p元素
<style>
.pclass:first-of-type
{
background:#ff0000;
}
</style>
</head>
<body>
<h1>這是一個標題</h1>
<p>這是第一個段落。</p>
<p class="pclass">這是第二個段落。</p>
</body>