CSS选择器超详细入门(零基础看懂) ## 一、什么是选择器? 语法结构: ```css 选择器 { 属性: 值; } ``` **选择器 = 用来选中页面里你想改样式的标签**,告诉浏览器:我要给谁设置样式。 --- # 二、最常用基础选择器(按学习顺序) ## 1. 通配符选择器 `*`(你刚才看到的) 选中页面**所有标签** ```css * { margin: 0; padding: 0; } ``` 用途:全局重置样式,写页面第一行常用。 ## 2. 元素(标签)选择器 直接写HTML标签名,**所有同名标签都会被选中** 示例HTML: ```html <p>段落1</p> <p>段落2</p> <div>盒子</div> ``` CSS: ```css /* 所有p标签变红色 */ p { color: red; } /* 所有div加背景 */ div { background: #eee; } ``` ## 3. class 类选择器 `.`(开发最常用) ### 规则 1. HTML标签上加 `class="名字"` 2. CSS用 `.类名` 选中 3. 一个页面可以多个标签用同一个class;一个标签能写多个class HTML: ```html <div class="box">盒子A</div> <div class="box">盒子B</div> <p class="text red">文字</p> ``` CSS: ```css /* 选中所有class=box的元素 */ .box { width: 100px; } /* 只选中带red类的 */ .red { color: red; } ``` ## 4. id选择器 `#` ### 规则 1. HTML写 `id="名字"` 2. CSS用 `#id名` 3. **一个页面id只能出现一次,不能重复**(唯一标识) HTML: ```html <div id="header">头部</div> ``` CSS: ```css #header { height: 60px; } ``` > 开发小建议:样式优先用class,id留给JS获取元素。 --- # 三、组合选择器(进阶,布局必用) ## 1. 后代选择器 空格 父 空格 子:选中父元素里面**所有后代**(儿子、孙子都算) ```html <div class="wrap"> <p>我会被选中</p> <div><p>我也会被选中</p></div> </div> <p>外面的p,不生效</p> ``` ```css .wrap p { color: blue; } ``` ## 2. 子代选择器 `>` 只选**直接儿子**,孙子不生效 ```css .wrap > p { /* 只选中wrap第一层的p,里面div包裹的p无效 */ } ``` ## 3. 并集选择器 `,` 逗号 一次性选中多个不同选择器,共用一套样式 ```css /* h1 h2 p 全部文字灰色 */ h1, h2, p { color: #666; } ``` ## 4. 相邻兄弟 `+` 紧挨着的下一个同级元素 ```css /* class为box后面紧挨着的第一个p */ .box + p { margin-top: 10px; } ``` ## 5. 通用兄弟 `~` 当前元素后面所有同级兄弟 ```css .box ~ p { /* box后面所有同级p标签 */ } ``` --- # 四、属性选择器(了解即可) 根据标签属性选中 ```html <input type="text"> <input type="password"> ``` ```css /* 选中type=text的input */ inputtype="text" { border: 1px solid #ccc; } ``` --- # 五、伪类选择器(交互效果) 给元素**某种状态**加样式,最常用: 1. `:hover` 鼠标放上去 ```css a:hover { color: orange; } .box:hover { background: pink; } ``` 2. `:active` 鼠标按住不放 3. `:first-child` 第一个子元素 4. `:last-child` 最后一个子元素 --- # 六、选择器权重(优先级,重点) 样式冲突时,权重高的生效,数字越大优先级越高: 1. `!important` 无穷大(尽量少用) 2. id选择器 #xxx → 100 3. class/属性/伪类 .xxx → 10 4. 标签选择器 div/p → 1 5. 通配符 * → 0 示例对比: - `#box` 权重100 > `.box` 权重10 > `div` 权重1 --- # 七、快速练习小案例 完整代码复制就能看效果 ```html <!DOCTYPE html> <html> <head> <style> * {margin:0;padding:0;box-sizing:border-box;} /* 标签选择器 */ p {font-size:16px;} /* class */ .title {font-size:24px;color:green;} /* id */ #top {background:#eee;padding:10px;} /* 后代 */ #top p {color:red;} /* 鼠标悬浮 */ .title:hover {color:orange;} </style> </head> <body> <div id="top"> <p class="title">标题</p> <p>普通段落</p> </div> <p>外面的段落</p> </body> </html> ``` 需要我出几道简单选择题,帮你巩固选择器吗?