CSS - 深入理解选择器的使用方式
warning:
这篇文章距离上次修改已过278天,其中的内容可能已经有所变动。
在CSS中,选择器是用于选择需要添加样式的HTML元素的模式。选择器有多种类型,包括基础选择器、组合选择器、属性选择器、伪类和伪元素选择器等。
以下是一些使用CSS选择器的示例:
- 基础选择器:
/* 标签选择器 */
p { color: blue; }
/* 类选择器 */
.my-class { background-color: yellow; }
/* ID选择器 */
#my-id { font-size: 20px; }
/* 通用选择器 */
* { margin: 0; padding: 0; }
- 组合选择器:
/* 交集选择器 */
p.my-class { color: red; } /* 选择拥有类my-class的所有p元素 */
/* 并集选择器 */
h1, h2, h3 { font-family: Arial, sans-serif; } /* 选择所有的h1、h2和h3元素 */
- 属性选择器:
/* 属性选择器 */
input[type="text"] { background-color: green; }
/* 带有特定属性值的选择器 */
div[class="container"] { border: 1px solid black; }
- 伪类选择器:
/* 链接伪类 */
a:link { color: blue; } /* 未访问的链接 */
a:visited { color: purple; } /* 已访问的链接 */
a:hover { color: red; } /* 鼠标悬停 */
a:active { color: yellow; } /* 选定的链接 */
/* 伪类选择器::first-child */
ul li:first-child { color: green; } /* 列表中的第一个元素 */
- 伪元素选择器:
/* 伪元素选择器 */
p::first-letter { font-size: 200%; } /* 段落的第一个字母 */
p::before { content: "[" attr(data-info) "] "; } /* 在元素内容前插入 */
CSS选择器是CSS的核心部分,了解和使用它们是每个前端开发人员必备的技能。
评论已关闭