10026---CSS 伪类

本文介绍了CSS伪类的使用方法,包括:first-child、:focus等,通过实例展示了如何选择元素的第一个子元素及如何使输入框获得焦点时背景颜色发生变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CSS - :first - child伪类

您可以使用 :first-child 伪类来选择元素的第一个子元素

注意:在IE8的之前版本必须声明<!DOCTYPE> ,这样 :first-child 才能生效。

匹配第一个 <p> 元素

在下面的例子中,选择器匹配作为任何元素的第一个子元素的 <p> 元素:

<html>
 <head>
 <style>
 p:first-child
 {
 color:blue;
 } 
 </style>
 </head>

 <body>
 <p>I am a strong man.</p>
 <p>I am a strong man.</p>
 </body>
 </html> 

匹配所有<p> 元素中的第一个 <i> 元素

在下面的例子中,选择相匹配的所有<p>元素的第一 <i>元素:

<html>
 <head>
 <style>
 p > i:first-child
 {
 color:blue;
 } 
 </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> 

===

<html>
 <head>
 <style>
 p:first-child i
 {
 color:blue;
 } 
 </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>

==

这个例子演示了如何使用 :focus伪类。

<style>
input:focus
{
background-color:yellow;
}
</style>
</head>

<body>
<form action="demo-form.php" method="get">
First name: <input type="text" name="fname" /><br>
Last name: <input type="text" name="lname" /><br>
<input type="submit" value="Submit" />
</form>

所有CSS伪类/元素

选择器示例示例说明
:linka:link选择所有未访问链接
:visiteda:visited选择所有访问过的链接
:activea:active选择正在活动链接
:hovera:hover把鼠标放在链接上的状态
:focusinput:focus选择元素输入后具有焦点
:first-letterp:first-letter选择每个<p> 元素的第一个字母
:first-linep:first-line选择每个<p> 元素的第一行
:first-childp:first-child选择器匹配属于任意元素的第一个子元素的 <]p> 元素
:beforep:beforeInsert content before every <p> element
:afterp:after在每个<p>元素之前插入内容
:lang(language)p:lang(it)为<p>元素的lang属性选择一个开始值






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值