CSS :first-child 选择器 | CSS 伪元素 | CSS教程

返回到:CSS 伪元素 | CSS教程

定义和用法

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

浏览器支持

表格中的数字表示支持该属性的第一个浏览器版本号。

选择器谷歌IE火狐苹果opera
:first-child4.07.03.03.19.6

注意: :first-child在IE8和更早版本IE版本中必须声明<!DOCTYPE>。

实例

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

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>Web176教程网(web176.com)</title> 
<style>
p:first-child
{
	background-color:yellow;
}
</style>
</head>
<body>

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

<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>注意:</b> :first-child作用于 IE8以及更早版本的浏览器, DOCTYPE必须已经声明.</p>

</body>
</html>

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

p:first-child i
{
    background:yellow;
}

列表中的第一个 <li>元素选择的样式:

li:first-child
{
    background:yellow;
}

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

ul>:first-child
{
    background:yellow;
}

作者:terry,如若转载,请注明出处:https://www.web176.com/cssprop/5322.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2022年2月21日 下午5:02
下一篇 2022年2月21日 下午5:12

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注