css :first-child选择器使用实例详解

时间:2016-08-03
css :first-child伪类选择器用于匹配父元素的第一个子元素,并为其设置css样式。本文章向大家介绍css :first-child的使用方法和基本使用实例,需要的朋友可以参考一下。

css :first-child介绍

css :first-child设置父元素的第一个子元素的样式表属性,即匹配父元素的第一个子元素,并为其设置css样式。例如:一个div中包括多个p元素,匹配第一个p元素可使用:first-child伪类

语法:

:first-child { 
   style properties 
}

比如:

body *:first-child {font-weight: bold;}
p:first-child  {font-size: 125%;}

css :first-child实例

先看如下一段代码,HTML部分:

<ul class="example">
    <li>aa</li>
    <li>bb</li>
    <li>cc</li>
    <li>dd</li>
</ul>

如果需要将第一个li的margin-left设为0px,则可以通过下面这个方法实现:

.example li:first-child{margin-left:10px;}

再看一个实例:匹配属于父元素中第一个子元素的每个<p>元素

<!DOCTYPE html>
<html>
<head>
<style>
p:first-child
{
background-color:yellow;
}
</style>
</head>
<body>

<p>This paragraph is the first child of its parent (body).</p>
/* http://www.manongjc.com/article/1304.html */
<h1>Welcome to My Homepage</h1>
<p>This paragraph is not the first child of its parent.</p>

<div>
<p>This paragraph is the first child of its parent (div).</p>
<p>This paragraph is not the first child of its parent.</p>
</div>

<p><b>Note:</b> For :first-child to work in IE8 and earlier, a DOCTYPE must be declared.</p>

</body>
</html>

在线运行