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

CSS3 :first-child选择器怎么用?
:first-child 选择器匹配其父元素中的第一个子元素。
语法:
元素:first-child
{
css样式
}例:匹配 <p> 的父元素的第一个<p>元素
立即学习“前端免费学习笔记(深入)”;
p:first-child
{
background-color:yellow;
}注释:所有主流浏览器都支持 :first-child 选择器。对于 IE8 及更早版本的浏览器中的 :first-child,必须声明 <!DOCTYPE>。
CSS :first-child选择器的使用示例
示例1:选择每个 <p> 中的每个 <i> 元素并设置其样式,其中的 <p> 元素是其父元素的第一个子元素:
<!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>效果图:

示例2:每一个<ul>元素的第一个子元素选择的样式
<!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>效果图:

以上就是CSS3 :first-child选择器怎么用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号