CSS常用选择器

CSS选择器用于选择HTML元素并为其应用样式。以下是CSS中最常用的选择器类型:

基本选择器

1.元素选择器 - 通过HTML标签名选择元素

p { color: blue; }

2.类选择器 - 通过class属性选择元素(以.开头)

.warning { color: red; }

3.ID选择器 - 通过id属性选择元素(以#开头)

#header { background: gray; }

4.通用选择器 - 选择所有元素(*)

* { margin: 0; padding: 0; }

组合选择器

5.后代选择器 - 选择某个元素内的所有特定后代(空格分隔)

div p { font-size: 14px; }

6.子元素选择器 - 选择直接子元素(>分隔)

ul > li { list-style: none; }

7.相邻兄弟选择器 - 选择紧接在另一个元素后的元素(+分隔)

h1 + p { margin-top: 0; }

8.通用兄弟选择器 - 选择所有在指定元素之后的同级元素(~分隔)

h2 ~ p { color: green; }

属性选择器

9.属性存在选择器 - 选择具有特定属性的元素

[disabled] { opacity: 0.5; }

10.属性值选择器 - 选择属性等于特定值的元素

[type="text"] { border: 1px solid #ccc; }

11.属性值包含选择器 - 选择属性值包含特定字符串的元素

[class*="btn"] { padding: 5px 10px; }

12.属性值开头选择器 - 选择属性值以特定字符串开头的元素

[href^="https"] { color: green; }

13.属性值结尾选择器 - 选择属性值以特定字符串结尾的元素

[src$=".png"] { border: 1px solid #eee; }

伪类选择器

14.动态伪类

a:link { color: blue; }        /* 未访问链接 */
a:visited { color: purple; }   /* 已访问链接 */
a:hover { text-decoration: underline; }  /* 鼠标悬停 */
a:active { color: red; }       /* 激活/点击时 */

15.结构伪类

li:first-child { font-weight: bold; }  /* 第一个子元素 */
li:last-child { border-bottom: none; } /* 最后一个子元素 */
li:nth-child(2n) { background: #f5f5f5; }  /* 偶数子元素 */

16.表单伪类

input:focus { outline: 2px solid blue; }
input:disabled { background: #eee; }
input:checked + label { font-weight: bold; }

伪元素选择器

17.伪元素

p::first-line { font-weight: bold; }  /* 第一行 */
p::first-letter { font-size: 2em; }   /* 首字母 */
::before { content: "→"; }            /* 在元素前插入内容 */
::after { content: "!"; }             /* 在元素后插入内容 */

选择器组合

18.多重选择器 - 同时选择多个元素(逗号分隔)

h1, h2, h3 { font-family: sans-serif; }

19.复合选择器 - 组合不同类型的选择器

button.primary { background: blue; }  /* 类为primary的button元素 */

这些选择器可以灵活组合使用,以满足各种样式需求。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浩~~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值