-
:first-child
鎖定
:first-child説明
利用 :first-child 這個偽類,只有當元素是另一個元素的第一個子元素時才能匹配。例如,p:first-child 會選擇作為另外某個元素第一個子元素的所有 p 元素。一般可能認為這會選擇作為段落第一個子元素的元素,但事實上並非如此,如果要選擇段落的第一個子元素,應當寫為 p >*:first-child。
:first-child瀏覽器支持
所有主流瀏覽器都支持:first-child。
注意::first-child在IE8中必須聲明<!DOCTYPE>.
[1]
:first-child實例
例子 1 - 匹配第一個 <p> 元素
在下面的例子中,選擇器匹配屬於任意元素的第一個子元素的 <p> 元素:
<style type="text/css"> p:first-child { font-weight:bold }</style> <p>I am a <em>strong</em> man. I am a <em>strong</em> man.</p> <p>I am a <em>strong</em> man. I am a <em>strong</em> man.</p>例子 2 - 匹配所有 <p> 元素中的第一個 <em> 元素 在本例中,選擇器匹配屬於 <p> 元素中的第一個子元素的 <em> 元素:
<style type="text/css"> p > em:first-child { font-weight:bold }</style> <p>I am a <em>strong</em> man. I am a <em>strong</em> man.</p> <p>I am a <em>strong</em> man. I am a <em>strong</em> man.</p>例子 3 - 匹配所有第一個子元素 <p> 元素中的所有 <em> 元素 在下面的例子中,選擇器匹配屬於其他元素的第一個子元素的 <p> 元素中的所有 <em>:
<style type="text/css"> p:first-child em { font-weight:bold }</style> <p>I am a <em>strong</em> man. I am a <em>strong</em> man.</p> <p>I am a <em>strong</em> man. I am a <em>strong</em> man.</p>
- 參考資料
-
- 1. CSS :first-child .W3Cschool[引用日期2018-04-26]
- 詞條統計
-
- 瀏覽次數:次
- 編輯次數:11次歷史版本
- 最近更新: thereforenay