伪类(Pseudo-classes)是CSS中的一种选择器,它允许你根据元素的状态或位置来选择元素,而不是直接依赖于文档树中的位置。伪类通过在选择器后面添加冒号(:)和一个特定的名称来表示。
:first-child
:选择父元素的第一个子元素。:last-child
:选择父元素的最后一个子元素。:nth-child(n)
:选择父元素的第n个子元素。:nth-last-child(n)
:选择父元素的倒数第n个子元素。:target
:选择当前活动的锚点目标元素。:hover
:选择鼠标悬停在其上的元素。:active
:选择用户激活(点击)的元素。:focus
:选择获得焦点的元素。:not(selector)
:选择不匹配指定选择器的元素。:hover
伪类来实现鼠标悬停时的样式变化。:focus
和:invalid
伪类来实现表单元素的焦点和验证状态样式。:first-child
和:last-child
伪类来实现列表项的首尾样式。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pseudo-class Example</title>
<style>
/* 鼠标悬停时的样式 */
a:hover {
color: red;
}
/* 表单元素获得焦点时的样式 */
input:focus {
border: 2px solid blue;
}
/* 列表项的首尾样式 */
ul li:first-child {
color: green;
}
ul li:last-child {
color: purple;
}
</style>
</head>
<body>
<ul>
<li>First item</li>
<li>Second item</li>
<li>Last item</li>
</ul>
<a href="#">Hover me</a>
<form>
<input type="text" placeholder="Focus on me">
</form>
</body>
</html>
通过使用伪类,你可以更灵活地控制页面的样式和交互效果,提升用户体验。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云