CSS3 :first-child选择器怎么用


本文摘自PHP中文网,作者青灯夜游,侵删。

CSS :first-child选择器用于匹配其父元素中的第一个子元素;即只有当元素是其父元素的第一个子元素时才会匹配元素。

CSS3 :first-child选择器怎么用

:first-child 选择器匹配其父元素中的第一个子元素。

语法:

1

2

3

4

元素:first-child

{

css样式

}

例:匹配 <p> 的父元素的第一个<p>元素

1

2

3

4

p:first-child

{

    background-color:yellow;

}

注释:所有主流浏览器都支持 :first-child 选择器。对于 IE8 及更早版本的浏览器中的 :first-child,必须声明 <!DOCTYPE>。

CSS :first-child选择器的使用示例

示例1:选择每个 <p> 中的每个 <i> 元素并设置其样式,其中的 <p> 元素是其父元素的第一个子元素:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<!DOCTYPE html>

<html>

<head>

<style>

p:first-child i

{

background:yellow;

}

</style>

</head>

<body>

<p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p>

<p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p>

</body>

</html>

效果图:

1.jpg

示例2:每一个<ul>元素的第一个子元素选择的样式

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<style>

ul>:first-child

{

background:yellow;

}

</style>

</head>

<body>

<ul>

  <li>Coffee</li>

  <li>Tea</li>

  <li>Coca Cola</li>

</ul>

<ul>

  <li>Coffee</li>

  <li>Tea</li>

  <li>Coca Cola</li>

</ul>

</body>

</html>

效果图:

2.jpg

以上就是CSS3 :first-child选择器怎么用的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

CSS3 appearance属性怎么用?

html如何取消文本选中

css <basic-shape>的基本形状函数有哪些?如何使用?

详解CSS3+svg滤镜实现不规则边框的方法

CSS3 text-justify属性怎么用

CSS3如何绘制半圆

h5移动端 超实用的CSS3模拟边框最新研究示例代码

CSS3怎么设置元素背面不可见

text-wrap属性怎么使用

CSS3中background-clip实现图片裁切3种效果(代码实例 )

更多相关阅读请进入《CSS3》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...