• 1.摘要
  • 2.基本信息
  • 3.说明
  • 4.浏览器支持
  • 5.实例
  • 6.参考资料

:first-child

:first-child伪类向元素的第一个子元素添加样式。

基本信息

  • 中文名

    first-child

  • 向元素

    伪类向元素

  • 应当写

    应当写为 p > *:first-child

  • 添加样式

    第一个子元素添加样式

说明

:first-child是CSS中的一个伪类适用于任何元素,它是另一个元素的第一个子元素。

利用 :first-child 这个伪类,只有当元素是另一个元素的第一个子元素时才能匹配。例如,p:first-child 会选择作为另外某个元素第一个子元素的所有 p 元素。一般可能认为这会选择作为段落第一个子元素的元素,但事实上并非如此,如果要选择段落的第一个子元素,应当写为 p > *:first-child。

浏览器支持

所有主流浏览器都支持:first-child。

注意::first-child在IE8中必须声明<!DOCTYPE>.1

实例

例子 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