CSS选择器详细教程

文章目录

    • 1. 基础概念
      • 1.1 什么是CSS选择器
      • 1.2 选择器的作用
      • 1.3 选择器的分类
    • 2. 基本选择器
      • 2.1 通用选择器 (*)
      • 2.2 类型选择器(元素选择器)
      • 2.3 类选择器 (.class)
      • 2.4 ID选择器 (#id)
      • 2.5 组合使用基本选择器
    • 3. 组合选择器
      • 3.1 后代选择器(空格)
      • 3.2 子选择器(>)
      • 3.3 相邻兄弟选择器(+)
      • 3.4 通用兄弟选择器(~)
    • 4. 属性选择器
      • 4.1 基本属性选择器
        • 4.1.1 [attr] - 选择具有指定属性的元素
        • 4.1.2 [attr=value] - 选择属性值完全匹配的元素
        • 4.1.3 [attr^=value] - 选择属性值以指定值开头的元素
        • 4.1.4 [attr$=value] - 选择属性值以指定值结尾的元素
        • 4.1.5 [attr*=value] - 选择属性值包含指定值的元素
        • 4.1.6 [attr~=value] - 选择属性值包含指定单词的元素
        • 4.1.7 [attr|=value] - 选择属性值等于指定值或以指定值-开头的元素
      • 4.2 高级属性选择器应用
        • 4.2.1 表单样式
        • 4.2.2 链接和媒体样式
        • 4.2.3 数据属性选择器
      • 4.3 属性选择器实际应用场景
        • 4.3.1 图标系统
        • 4.3.2 响应式设计
        • 4.3.3 表格样式
    • 5. 伪类选择器
      • 5.1 链接和用户行为伪类
        • 5.1.1 基本链接状态
        • 5.1.2 用户交互伪类
      • 5.2 结构伪类选择器
        • 5.2.1 子元素位置选择器
        • 5.2.2 类型相关的位置选择器
      • 5.3 表单相关伪类
        • 5.3.1 表单状态伪类
        • 5.3.2 选择状态伪类
      • 5.4 内容相关伪类
    • 6. 伪元素选择器
      • 6.1 基本伪元素
        • 6.1.1 ::before和::after
        • 6.1.2 ::first-line和::first-letter
      • 6.2 高级伪元素应用
        • 6.2.1 装饰和图形
    • 7. 选择器优先级
      • 7.1 优先级计算规则
      • 7.2 优先级最佳实践
    • 8. 性能优化
      • 8.1 高效选择器编写
      • 8.2 选择器优化建议
    • 9. 实际应用场景
      • 9.1 响应式导航菜单
      • 9.2 表单验证样式
    • 10. 最佳实践
      • 10.1 选择器命名规范
      • 10.2 选择器组织结构
    • 11. 常见问题
      • 11.1 选择器问题排查
      • 11.2 兼容性注意事项
    • 12. 总结
      • 12.1 选择器使用建议
      • 12.2 学习建议

1. 基础概念

1.1 什么是CSS选择器

CSS选择器是一种模式,用于选择HTML文档中的元素,以便对这些元素应用样式。选择器是CSS规则的重要组成部分。

CSS规则的基本结构:

选择器 {
    属性:;
    属性:;
}

示例:

h1 {
    color: blue;
    font-size: 24px;
}

1.2 选择器的作用

  1. 精确定位元素 - 选择特定的HTML元素
  2. 批量样式应用 - 对多个元素应用相同样式
  3. 条件性选择 - 根据元素状态或位置选择
  4. 层次结构控制 - 基于元素关系选择

1.3 选择器的分类

CSS选择器
├── 基本选择器
│   ├── 通用选择器 (*)
│   ├── 类型选择器 (元素名)
│   ├── 类选择器 (.class)
│   └── ID选择器 (#id)
├── 组合选择器
│   ├── 后代选择器 (空格)
│   ├── 子选择器 (>)
│   ├── 相邻兄弟选择器 (+)
│   └── 通用兄弟选择器 (~)
├── 属性选择器
│   ├── [attr]
│   ├── [attr=value]
│   ├── [attr^=value]
│   └── 更多...
├── 伪类选择器
│   ├── :hover
│   ├── :active
│   ├── :first-child
│   └── 更多...
└── 伪元素选择器
    ├── ::before
    ├── ::after
    ├── ::first-line
    └── 更多...

2. 基本选择器

2.1 通用选择器 (*)

通用选择器选择页面上的所有元素。

语法:

* {
    /* 样式规则 */
}

示例:

/* 重置所有元素的内外边距 */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

/* 为所有元素添加边框 */
* {
    border: 1px solid red;
}

HTML示例:

DOCTYPE html>
<html>
<head>
    <style>
        * {
            margin: 0;
            padding: 0;
            border: 1px solid #ccc;
        }
    style>
head>
<body>
    <h1>标题h1>
    <p>段落文字p>
    <div>div元素div>
    
body>
html>

使用场景:

  • CSS重置样式
  • 全局样式设置
  • 调试布局问题

2.2 类型选择器(元素选择器)

类型选择器根据HTML元素的标签名选择元素。

语法:

元素名 {
    /* 样式规则 */
}

基础示例:

/* 选择所有段落元素 */
p {
    color: blue;
    font-size: 16px;
    line-height: 1.5;
}

/* 选择所有标题元素 */
h1 {
    color: red;
    font-size: 32px;
    text-align: center;
}

/* 选择所有div元素 */
div {
    background-color: lightgray;
    padding: 10px;
    margin: 5px;
}

HTML示例:

DOCTYPE html>
<html>
<head>
    <style>
        h1 {
            color: navy;
            font-family: Arial, sans-serif;
            text-align: center;
        }
        
        p {
            color: darkgray;
            margin: 15px 0;
            text-indent: 20px;
        }
        
        ul {
            list-style-type: square;
            margin-left: 20px;
        }
        
        li {
            margin: 5px 0;
            color: green;
        }
    style>
head>
<body>
    <h1>网页标题h1>
    <p>这是第一段文字,会应用段落样式。p>
    <p>这是第二段文字,同样会应用段落样式。p>
    
    <ul>
        <li>列表项1li>
        <li>列表项2li>
        <li>列表项3li>
    ul>
body>
html>

高级示例:

/* 选择所有输入框 */
input {
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

/* 选择所有按钮 */
button {
    background-color: #007bff;
    color: white;
    padding: 10px 15px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

/* 选择所有表格 */
table {
    border-collapse: collapse;
    width: 100%;
}

/* 选择所有表格单元格 */
td, th {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
}

2.3 类选择器 (.class)

类选择器选择具有特定class属性值的元素。

语法:

.类名 {
    /* 样式规则 */
}

基础示例:

/* 选择class为highlight的元素 */
.highlight {
    background-color: yellow;
    font-weight: bold;
}

/* 选择class为error的元素 */
.error {
    color: red;
    border: 2px solid red;
    padding: 10px;
}

/* 选择class为success的元素 */
.success {
    color: green;
    background-color: #d4edda;
    border: 1px solid #c3e6cb;
    padding: 10px;
    border-radius: 5px;
}

HTML示例:

DOCTYPE html>
<html>
<head>
    <style>
        .header {
            background-color: #333;
            color: white;
            padding: 20px;
            text-align: center;
        }
        
        .content {
            max-width: 800px;
            margin: 20px auto;
            padding: 20px;
        }
        
        .highlight {
            background-color: #ffeb3b;
            padding: 5px;
            border-radius: 3px;
        }
        
        .warning {
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
            color: #856404;
            padding: 15px;
            border-radius: 5px;
            margin: 10px 0;
        }
        
        .button {
            display: inline-block;
            padding: 12px 24px;
            background-color: #007bff;
            color: white;
            text-decoration: none;
            border-radius: 5px;
            transition: background-color 0.3s;
        }
        
        .button:hover {
            background-color: #0056b3;
        }
    style>
head>
<body>
    <div class="header">
        <h1>我的网站h1>
    div>
    
    <div class="content">
        <p>这是一段普通文字。p>
        <p>这段文字包含<span class="highlight">高亮内容span>p>
        
        <div class="warning">
            ⚠️ 这是一个警告消息框。
        div>
        
        <a href="#" class="button">点击按钮a>
    div>
body>
html>

多类名示例:

/* 元素可以同时具有多个类名 */
.btn {
    padding: 10px 15px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
}

.btn-primary {
    background-color: #007bff;
    color: white;
}

.btn-danger {
    background-color: #dc3545;
    color: white;
}

.btn-large {
    font-size: 18px;
    padding: 15px 25px;
}

<button class="btn btn-primary">主要按钮button>
<button class="btn btn-danger">危险按钮button>
<button class="btn btn-primary btn-large">大号主要按钮button>

2.4 ID选择器 (#id)

ID选择器选择具有特定id属性值的元素。ID在页面中应该是唯一的。

语法:

#ID名 {
    /* 样式规则 */
}

基础示例:

/* 选择id为header的元素 */
#header {
    background-color: #2c3e50;
    color: white;
    height: 80px;
    line-height: 80px;
    text-align: center;
}

/* 选择id为main-content的元素 */
#main-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
}

/* 选择id为footer的元素 */
#footer {
    background-color: #34495e;
    color: white;
    text-align: center;
    padding: 20px 0;
    position: fixed;
    bottom: 0;
    width: 100%;
}

HTML示例:

DOCTYPE html>
<html>
<head>
    <style>
        #navigation {
            background-color: #333;
            padding: 0;
            margin: 0;
            list-style-type: none;
            overflow: hidden;
        }
        
        #navigation li {
            float: left;
        }
        
        #navigation li a {
            display: block;
            color: white;
            text-align: center;
            padding: 14px 20px;
            text-decoration: none;
        }
        
        #navigation li a:hover {
            background-color: #555;
        }
        
        #sidebar {
            width: 25%;
            float: left;
            background-color: #f1f1f1;
            padding: 20px;
            box-sizing: border-box;
        }
        
        #main-article {
            width: 75%;
            float: left;
            padding: 20px;
            box-sizing: border-box;
        }
        
        #contact-form {
            background-color: #e9ecef;
            padding: 30px;
            border-radius: 10px;
            margin: 20px 0;
        }
        
        #submit-button {
            background-color: #28a745;
            color: white;
            padding: 12px 30px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }
        
        #submit-button:hover {
            background-color: #218838;
        }
    style>
head>
<body>
    <ul id="navigation">
        <li><a href="#home">首页a>li>
        <li><a href="#about">关于a>li>
        <li><a href="#services">服务a>li>
        <li><a href="#contact">联系a>li>
    ul>
    
    <div id="sidebar">
        <h3>侧边栏h3>
        <p>这里是侧边栏内容。p>
    div>
    
    <div id="main-article">
        <h2>主要文章h2>
        <p>这里是主要内容区域。p>
    div>
    
    <div id="contact-form">
        <h3>联系表单h3>
        <form>
            <input type="text" placeholder="姓名">
            <input type="email" placeholder="邮箱">
            <button id="submit-button" type="submit">提交button>
        form>
    div>
body>
html>

注意事项:

/* ❌ 错误:ID应该是唯一的 */
#unique-id { color: red; }

<div id="unique-id">内容1div>
<div id="unique-id">内容2div>


<div id="content-1">内容1div>
<div id="content-2">内容2div>

2.5 组合使用基本选择器

/* 组合选择器:选择具有特定类的特定元素 */
p.highlight {
    background-color: yellow;
    font-weight: bold;
}

/* 选择具有特定ID的特定元素 */
div#main-container {
    max-width: 1200px;
    margin: 0 auto;
}

/* 选择具有多个类的元素 */
.btn.primary {
    background-color: #007bff;
}

.btn.danger {
    background-color: #dc3545;
}

/* 复杂组合 */
ul.nav-menu li.active a {
    color: #007bff;
    font-weight: bold;
}

HTML示例:

<p>普通段落p>
<p class="highlight">高亮段落p>
<div>普通divdiv>
<div id="main-container">主容器divdiv>

<button class="btn">普通按钮button>
<button class="btn primary">主要按钮button>
<button class="btn danger">危险按钮button>

<ul class="nav-menu">
    <li><a href="#">首页a>li>
    <li class="active"><a href="#">当前页a>li>
    <li><a href="#">其他页a>li>
ul>

3. 组合选择器

组合选择器允许根据元素之间的关系来选择元素。

3.1 后代选择器(空格)

后代选择器选择某个元素内部的所有指定后代元素(不限于直接子元素)。

语法:

父元素 后代元素 {
    /* 样式规则 */
}

基础示例:

/* 选择所有div内部的p元素 */
div p {
    color: blue;
    margin: 10px 0;
}

/* 选择header内部的所有a链接 */
header a {
    color: white;
    text-decoration: none;
}

/* 选择nav内部的所有li元素 */
nav li {
    display: inline-block;
    margin: 0 10px;
}

HTML示例:

DOCTYPE html>
<html>
<head>
    <style>
        /* 选择article内部的所有h2标题 */
        article h2 {
            color: #2c3e50;
            border-bottom: 2px solid #3498db;
            padding-bottom: 10px;
        }
        
        /* 选择sidebar内部的所有链接 */
        .sidebar a {
            display: block;
            padding: 8px 15px;
            color: #333;
            text-decoration: none;
            border-bottom: 1px solid #eee;
        }
        
        .sidebar a:hover {
            background-color: #f8f9fa;
        }
        
        /* 选择footer内部的所有段落 */
        footer p {
            margin: 5px 0;
            color: #6c757d;
            font-size: 14px;
        }
        
        /* 深层嵌套选择 */
        .content .post .meta span {
            color: #999;
            font-size: 12px;
            margin-right: 10px;
        }
    style>
head>
<body>
    <article>
        <h2>文章标题h2>
        <p>文章内容...p>
        <div class="post">
            <div class="meta">
                <span>作者:张三span>
                <span>时间:2024-01-01span>
            div>
        div>
    article>
    
    <div class="sidebar">
        <h3>侧边栏h3>
        <a href="#">链接1a>
        <a href="#">链接2a>
        <a href="#">链接3a>
    div>
    
    <footer>
        <p>版权所有 © 2024p>
        <p>联系邮箱:[email protected]p>
    footer>
body>
html>

3.2 子选择器(>)

子选择器只选择某个元素的直接子元素。

语法:

父元素 > 直接子元素 {
    /* 样式规则 */
}

基础示例:

/* 只选择ul的直接子元素li */
ul > li {
    list-style-type: disc;
    margin: 5px 0;
}

/* 只选择div的直接子元素p */
div > p {
    font-weight: bold;
}

/* 只选择nav的直接子元素ul */
nav > ul {
    display: flex;
    list-style: none;
    margin: 0;
    padding: 0;
}

对比示例:

DOCTYPE html>
<html>
<head>
    <style>
        /* 后代选择器:选择所有嵌套的span */
        .container span {
            color: red;
        }
        
        /* 子选择器:只选择直接子元素span */
        .container > span {
            background-color: yellow;
        }
        
        /* 对比展示 */
        .demo1 p {
            color: blue; /* 选择所有p元素 */
        }
        
        .demo2 > p {
            color: green; /* 只选择直接子p元素 */
        }
    style>
head>
<body>
    <div class="container">
        <span>直接子元素span(红色+黄色背景)span>
        <div>
            <span>嵌套的span(只有红色)span>
        div>
    div>
    
    <div class="demo1">
        <p>直接子元素p(蓝色)p>
        <div>
            <p>嵌套的p(蓝色)p>
        div>
    div>
    
    <div class="demo2">
        <p>直接子元素p(绿色)p>
        <div>
            <p>嵌套的p(默认黑色)p>
        div>
    div>
body>
html>

3.3 相邻兄弟选择器(+)

相邻兄弟选择器选择紧接在另一个元素后的元素,且它们具有相同的父元素。

语法:

元素1 + 元素2 {
    /* 样式规则 */
}

基础示例:

/* 选择紧跟在h2后面的p元素 */
h2 + p {
    font-weight: bold;
    margin-top: 0;
    color: #666;
}

/* 选择紧跟在img后面的p元素 */
img + p {
    font-style: italic;
    margin-top: 10px;
}

/* 选择紧跟在label后面的input元素 */
label + input {
    margin-left: 10px;
}

HTML示例:

DOCTYPE html>
<html>
<head>
    <style>
        /* 标题后的第一段特殊样式 */
        h1 + p {
            font-size: 18px;
            color: #555;
            font-weight: 300;
            margin-bottom: 20px;
        }
        
        /* 图片后紧跟的段落作为图片说明 */
        img + p {
            font-size: 14px;
            color: #777;
            font-style: italic;
            text-align: center;
            margin-top: 5px;
        }
        
        /* 复选框后紧跟的标签样式 */
        input[type="checkbox"] + label {
            margin-left: 8px;
            cursor: pointer;
            user-select: none;
        }
        
        /* 单选按钮后的标签 */
        input[type="radio"] + label {
            margin-left: 5px;
            margin-right: 15px;
            cursor: pointer;
        }
        
        /* 表单字段后的错误消息 */
        .error + .error-message {
            color: red;
            font-size: 12px;
            margin-top: 2px;
            display: block;
        }
    style>
head>
<body>
    <article>
        <h1>文章标题h1>
        <p>这是标题后的第一段,会有特殊样式。p>
        <p>这是普通段落。p>
        
        <img src="image.jpg" alt="示例图片" width="300">
        <p>这是图片说明文字。p>
        
        <form>
            <input type="checkbox" id="agree">
            <label for="agree">我同意条款label>
            <br><br>
            
            <input type="radio" id="male" name="gender">
            <label for="male">label>
            <input type="radio" id="female" name="gender">
            <label for="female">label>
            <br><br>
            
            <input type="text" class="error" placeholder="用户名">
            <span class="error-message">用户名不能为空span>
        form>
    article>
body>
html>

3.4 通用兄弟选择器(~)

通用兄弟选择器选择某个元素后面的所有兄弟元素(不要求紧邻)。

语法:

元素1 ~ 元素2 {
    /* 样式规则 */
}

基础示例:

/* 选择h2后面的所有p元素 */
h2 ~ p {
    margin-left: 20px;
    border-left: 3px solid #007bff;
    padding-left: 15px;
}

/* 选择选中的单选按钮后面的所有标签 */
input:checked ~ label {
    color: green;
    font-weight: bold;
}

/* 选择悬停元素后面的所有兄弟元素 */
.item:hover ~ .item {
    opacity: 0.5;
}

HTML示例:

DOCTYPE html>
<html>
<head>
    <style>
        /* 标题后的所有段落缩进 */
        h3 ~ p {
            margin-left: 30px;
            color: #666;
        }
        
        /* 标题后的所有列表缩进 */
        h3 ~ ul {
            margin-left: 30px;
        }
        
        /* 激活状态的兄弟元素效果 */
        .tab.active ~ .tab {
            background-color: #f8f9fa;
        }
        
        /* 选中状态影响后续元素 */
        input[type="radio"]:checked ~ .content {
            display: block;
        }
        
        .content {
            display: none;
            padding: 20px;
            background-color: #e9ecef;
            margin-top: 10px;
        }
        
        /* 悬停效果影响兄弟元素 */
        .gallery-item:hover ~ .gallery-item {
            opacity: 0.3;
            transition: opacity 0.3s;
        }
        
        .gallery-item {
            display: inline-block;
            width: 100px;
            height: 100px;
            background-color: #007bff;
            margin: 5px;
            transition: opacity 0.3s;
        }
    style>
head>
<body>
    <article>
        <h3>章节标题h3>
        <p>这个段落会被缩进。p>
        <p>这个段落也会被缩进。p>
        <ul>
            <li>这个列表也会被缩进li>
            <li>列表项2li>
        ul>
        <p>这个段落同样会被缩进。p>
    article>
    
    <div class="tabs">
        <div class="tab active">标签1div>
        <div class="tab">标签2div>
        <div class="tab">标签3div>
    div>
    
    <form>
        <input type="radio" id="option1" name="options">
        <label for="option1">选项1label>
        <div class="content">选项1的内容div>
        
        <input type="radio" id="option2" name="options">
        <label for="option2">选项2label>
        <div class="content">选项2的内容div>
    form>
    
    <div class="gallery">
        <div class="gallery-item">div>
        <div class="gallery-item">div>
        <div class="gallery-item">div>
        <div class="gallery-item">div>
    div>
body>
html>

4. 属性选择器

属性选择器根据元素的属性及其值来选择元素。

4.1 基本属性选择器

4.1.1 [attr] - 选择具有指定属性的元素
/* 选择所有具有title属性的元素 */
[title] {
    cursor: help;
    border-bottom: 1px dotted #999;
}

/* 选择所有具有disabled属性的输入框 */
input[disabled] {
    background-color: #f5f5f5;
    color: #999;
    cursor: not-allowed;
}

/* 选择所有具有required属性的元素 */
[required] {
    border-left: 3px solid #ff0000;
}
4.1.2 [attr=value] - 选择属性值完全匹配的元素
/* 选择type为text的输入框 */
input[type="text"] {
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

/* 选择class为button的元素 */
[class="button"] {
    background-color: #007bff;
    color: white;
    padding: 10px 15px;
}

/* 选择target为_blank的链接 */
a[target="_blank"] {
    color: #e74c3c;
}

a[target="_blank"]::after {
    content: " ↗";
    font-size: 12px;
}
4.1.3 [attr^=value] - 选择属性值以指定值开头的元素
/* 选择href以https开头的链接 */
a[href^="https"] {
    color: green;
}

a[href^="https"]::before {
    content: " ";
}

/* 选择class以btn开头的元素 */
[class^="btn"] {
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
    border: none;
    border-radius: 4px;
}

/* 选择id以modal开头的元素 */
[id^="modal"] {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
4.1.4 [attr$=value] - 选择属性值以指定值结尾的元素
/* 选择href以.pdf结尾的链接 */
a[href$=".pdf"] {
    color: #dc3545;
}

a[href$=".pdf"]::after {
    content: " ";
}

/* 选择src以.jpg结尾的图片 */
img[src$=".jpg"],
img[src$=".jpeg"],
img[src$=".png"] {
    border: 2px solid #ddd;
    border-radius: 4px;
}

/* 选择class以-large结尾的元素 */
[class$="-large"] {
    font-size: 1.2em;
    padding: 12px 20px;
}
4.1.5 [attr*=value] - 选择属性值包含指定值的元素
/* 选择title包含"重要"的元素 */
[title*="重要"] {
    background-color: #fff3cd;
    border: 1px solid #ffeaa7;
}

/* 选择class包含nav的元素 */
[class*="nav"] {
    list-style: none;
    padding: 0;
    margin: 0;
}

/* 选择href包含github的链接 */
a[href*="github"] {
    color: #333;
}

a[href*="github"]::before {
    content: "⭐ ";
}
4.1.6 [attr~=value] - 选择属性值包含指定单词的元素
/* 选择class包含highlight单词的元素 */
[class~="highlight"] {
    background-color: yellow;
    font-weight: bold;
}

/* 选择title包含提示单词的元素 */
[title~="提示"] {
    cursor: help;
}
4.1.7 [attr|=value] - 选择属性值等于指定值或以指定值-开头的元素
/* 选择lang为zh或以zh-开头的元素 */
[lang|="zh"] {
    font-family: "SimHei", "Microsoft YaHei", sans-serif;
}

/* 选择data-theme为dark或以dark-开头的元素 */
[data-theme|="dark"] {
    background-color: #333;
    color: white;
}

4.2 高级属性选择器应用

4.2.1 表单样式
DOCTYPE html>
<html>
<head>
    <style>
        /* 表单基础样式 */
        form {
            max-width: 500px;
            margin: 20px auto;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 8px;
        }
        
        /* 所有输入框基础样式 */
        input[type="text"],
        input[type="email"],
        input[type="password"],
        input[type="tel"],
        input[type="url"] {
            width: 100%;
            padding: 10px;
            margin: 5px 0 15px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        
        /* 必填字段样式 */
        input[required] {
            border-left: 3px solid #007bff;
        }
        
        /* 只读字段样式 */
        input[readonly] {
            background-color: #f8f9fa;
            cursor: not-allowed;
        }
        
        /* 禁用字段样式 */
        input[disabled] {
            background-color: #e9ecef;
            color: #6c757d;
            cursor: not-allowed;
        }
        
        /* 有效输入框样式 */
        input:valid {
            border-color: #28a745;
        }
        
        /* 无效输入框样式 */
        input:invalid {
            border-color: #dc3545;
        }
        
        /* 占位符样式 */
        input[placeholder] {
            font-style: italic;
        }
        
        /* 自动完成样式 */
        input[autocomplete="off"] {
            background-color: #fff3cd;
        }
        
        /* 按钮样式 */
        button[type="submit"] {
            background-color: #007bff;
            color: white;
            padding: 12px 30px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        
        button[type="reset"] {
            background-color: #6c757d;
            color: white;
            padding: 12px 30px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 10px;
        }
        
        /* 文件上传样式 */
        input[type="file"] {
            padding: 8px;
            border: 2px dashed #007bff;
            background-color: #f8f9fa;
        }
        
        /* 多选和单选样式 */
        input[type="checkbox"],
        input[type="radio"] {
            margin-right: 8px;
            transform: scale(1.2);
        }
    style>
head>
<body>
    <form>
        <input type="text" placeholder="用户名" required>
        <input type="email" placeholder="邮箱地址" required>
        <input type="password" placeholder="密码" required>
        <input type="text" value="只读字段" readonly>
        <input type="text" value="禁用字段" disabled>
        <input type="file" accept=".jpg,.png,.pdf">
        
        <label>
            <input type="checkbox" required>
            我同意服务条款
        label>
        
        <br><br>
        
        <button type="submit">提交button>
        <button type="reset">重置button>
    form>
body>
html>
4.2.2 链接和媒体样式
/* 不同类型链接的样式 */
a[href^="http://"] {
    color: #007bff;
}

a[href^="https://"] {
    color: #28a745;
}

a[href^="mailto:"] {
    color: #6c757d;
}

a[href^="mailto:"]::before {
    content: "✉ ";
}

a[href^="tel:"] {
    color: #17a2b8;
}

a[href^="tel:"]::before {
    content: " ";
}

/* 下载链接样式 */
a[download] {
    background-color: #e9ecef;
    padding: 5px 10px;
    border-radius: 3px;
    text-decoration: none;
}

a[download]::after {
    content: " ⬇";
    font-weight: bold;
}

/* 图片样式 */
img[alt] {
    border: 1px solid #ddd;
}

img[title] {
    cursor: help;
}

/* 响应式图片 */
img[sizes] {
    max-width: 100%;
    height: auto;
}

/* 视频样式 */
video[controls] {
    width: 100%;
    max-width: 600px;
}

video[autoplay] {
    border: 2px solid #dc3545;
}
4.2.3 数据属性选择器
DOCTYPE html>
<html>
<head>
    <style>
        /* 数据状态样式 */
        [data-status="active"] {
            background-color: #d4edda;
            border-color: #c3e6cb;
            color: #155724;
        }
        
        [data-status="inactive"] {
            background-color: #f8d7da;
            border-color: #f5c6cb;
            color: #721c24;
        }
        
        [data-status="pending"] {
            background-color: #fff3cd;
            border-color: #ffeaa7;
            color: #856404;
        }
        
        /* 数据优先级样式 */
        [data-priority="high"] {
            border-left: 5px solid #dc3545;
            font-weight: bold;
        }
        
        [data-priority="medium"] {
            border-left: 5px solid #ffc107;
        }
        
        [data-priority="low"] {
            border-left: 5px solid #28a745;
        }
        
        /* 数据角色样式 */
        [data-role="admin"] {
            background-color: #007bff;
            color: white;
            padding: 5px 10px;
            border-radius: 3px;
        }
        
        [data-role="user"] {
            background-color: #6c757d;
            color: white;
            padding: 5px 10px;
            border-radius: 3px;
        }
        
        /* 数据主题样式 */
        [data-theme="dark"] {
            background-color: #333;
            color: white;
        }
        
        [data-theme="light"] {
            background-color: white;
            color: #333;
        }
        
        /* 数据尺寸样式 */
        [data-size="small"] {
            font-size: 12px;
            padding: 4px 8px;
        }
        
        [data-size="medium"] {
            font-size: 14px;
            padding: 8px 12px;
        }
        
        [data-size="large"] {
            font-size: 18px;
            padding: 12px 16px;
        }
    style>
head>
<body>
    <div data-status="active" data-priority="high">
        高优先级活跃项目
    div>
    
    <div data-status="inactive" data-priority="medium">
        中优先级非活跃项目
    div>
    
    <div data-status="pending" data-priority="low">
        低优先级待处理项目
    div>
    
    <span data-role="admin">管理员span>
    <span data-role="user">普通用户span>
    
    <div data-theme="dark" data-size="large">
        深色主题大号文字
    div>
    
    <div data-theme="light" data-size="small">
        浅色主题小号文字
    div>
body>
html>

4.3 属性选择器实际应用场景

4.3.1 图标系统
/* 基于data属性的图标系统 */
[data-icon]::before {
    font-family: 'Font Awesome';
    margin-right: 5px;
}

[data-icon="user"]::before {
    content: "\f007";
}

[data-icon="home"]::before {
    content: "\f015";
}

[data-icon="email"]::before {
    content: "\f0e0";
}

[data-icon="phone"]::before {
    content: "\f095";
}

/* 文件类型图标 */
a[href$=".pdf"]::before {
    content: " ";
    color: #dc3545;
}

a[href$=".doc"]::before,
a[href$=".docx"]::before {
    content: " ";
    color: #007bff;
}

a[href$=".xls"]::before,
a[href$=".xlsx"]::before {
    content: " ";
    color: #28a745;
}

a[href$=".zip"]::before,
a[href$=".rar"]::before {
    content: " ";
    color: #6c757d;
}
4.3.2 响应式设计
/* 基于属性的响应式组件 */
[data-responsive="true"] {
    width: 100%;
    max-width: 100%;
}

@media (min-width: 768px) {
    [data-responsive="true"][data-md="6"] {
        width: 50%;
    }
    
    [data-responsive="true"][data-md="4"] {
        width: 33.333%;
    }
    
    [data-responsive="true"][data-md="3"] {
        width: 25%;
    }
}

@media (min-width: 992px) {
    [data-responsive="true"][data-lg="6"] {
        width: 50%;
    }
    
    [data-responsive="true"][data-lg="4"] {
        width: 33.333%;
    }
    
    [data-responsive="true"][data-lg="3"] {
        width: 25%;
    }
}
4.3.3 表格样式
/* 表格属性选择器 */
table[border] {
    border-collapse: collapse;
}

th[scope="col"] {
    background-color: #f8f9fa;
    text-align: left;
    font-weight: bold;
}

th[scope="row"] {
    background-color: #e9ecef;
    font-weight: bold;
}

td[rowspan] {
    vertical-align: middle;
    background-color: #fff3cd;
}

td[colspan] {
    text-align: center;
    font-weight: bold;
    background-color: #d4edda;
}

/* 可排序表头 */
th[data-sortable="true"] {
    cursor: pointer;
    user-select: none;
}

th[data-sortable="true"]:hover {
    background-color: #e9ecef;
}

th[data-sort="asc"]::after {
    content: " ↑";
    color: #007bff;
}

th[data-sort="desc"]::after {
    content: " ↓";
    color: #007bff;
}

5. 伪类选择器

伪类选择器用于选择处于特定状态的元素。

5.1 链接和用户行为伪类

5.1.1 基本链接状态
/* 链接的四种基本状态(按顺序:LVHA) */
a:link {
    color: #007bff;          /* 未访问的链接 */
    text-decoration: none;
}

a:visited {
    color: #6c757d;          /* 已访问的链接 */
}

a:hover {
    color: #0056b3;          /* 鼠标悬停 */
    text-decoration: underline;
}

a:active {
    color: #003d82;          /* 点击时 */
    background-color: #e9ecef;
}

/* 焦点状态 */
a:focus {
    outline: 2px solid #007bff;
    outline-offset: 2px;
}
5.1.2 用户交互伪类
/* 悬停效果 */
button:hover {
    background-color: #0056b3;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}

/* 活跃状态 */
button:active {
    transform: translateY(0);
    box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

/* 焦点状态 */
input:focus {
    border-color: #007bff;
    box-shadow: 0 0 0 0.2rem rgba(0,123,255,0.25);
    outline: none;
}

/* 禁用状态 */
button:disabled {
    background-color: #6c757d;
    cursor: not-allowed;
    opacity: 0.6;
}

/* 只读状态 */
input:read-only {
    background-color: #f8f9fa;
    cursor: default;
}

5.2 结构伪类选择器

5.2.1 子元素位置选择器
/* 第一个子元素 */
li:first-child {
    border-top: 2px solid #007bff;
    font-weight: bold;
}

/* 最后一个子元素 */
li:last-child {
    border-bottom: 2px solid #007bff;
    margin-bottom: 20px;
}

/* 唯一子元素 */
p:only-child {
    text-align: center;
    font-style: italic;
}

/* 第n个子元素 */
tr:nth-child(odd) {
    background-color: #f8f9fa;
}

tr:nth-child(even) {
    background-color: white;
}

/* 特定位置 */
li:nth-child(3) {
    color: #dc3545;
    font-weight: bold;
}

/* 每3个元素 */
.grid-item:nth-child(3n) {
    margin-right: 0;
}

/* 前3个元素 */
.item:nth-child(-n+3) {
    background-color: #fff3cd;
}

/* 后3个元素 */
.item:nth-last-child(-n+3) {
    border-bottom: 2px solid #28a745;
}
5.2.2 类型相关的位置选择器
/* 同类型元素的第一个 */
h2:first-of-type {
    margin-top: 0;
    color: #007bff;
}

/* 同类型元素的最后一个 */
p:last-of-type {
    margin-bottom: 30px;
}

/* 同类型的第n个 */
img:nth-of-type(2n) {
    float: right;
    margin-left: 20px;
}

/* 同类型的唯一元素 */
article:only-of-type {
    max-width: 800px;
    margin: 0 auto;
}

5.3 表单相关伪类

5.3.1 表单状态伪类
/* 必填字段 */
input:required {
    border-left: 3px solid #dc3545;
}

/* 可选字段 */
input:optional {
    border-left: 3px solid #28a745;
}

/* 有效输入 */
input:valid {
    border-color: #28a745;
    background-image: url('checkmark.svg');
    background-repeat: no-repeat;
    background-position: right 10px center;
}

/* 无效输入 */
input:invalid {
    border-color: #dc3545;
    background-color: #f8d7da;
}

/* 超出范围 */
input:out-of-range {
    border-color: #ffc107;
    background-color: #fff3cd;
}

/* 在范围内 */
input:in-range {
    border-color: #28a745;
}
5.3.2 选择状态伪类
/* 选中的单选框和复选框 */
input:checked {
    transform: scale(1.1);
}

/* 未确定状态 */
input:indeterminate {
    opacity: 0.5;
}

/* 默认选中 */
option:default {
    background-color: #e9ecef;
    font-weight: bold;
}

5.4 内容相关伪类

/* 空元素 */
p:empty {
    display: none;
}

/* 包含特定文本的元素(CSS4,浏览器支持有限) */
p:contains("重要") {
    background-color: #fff3cd;
    font-weight: bold;
}

/* 不匹配选择器的元素 */
input:not([type="submit"]) {
    margin-bottom: 10px;
}

/* 复杂的:not选择器 */
li:not(.active):not(.disabled) {
    opacity: 0.7;
}

6. 伪元素选择器

伪元素选择器用于创建和样式化元素的特定部分。

6.1 基本伪元素

6.1.1 ::before和::after
/* 在元素前添加内容 */
.quote::before {
    content: """;
    font-size: 2em;
    color: #007bff;
    vertical-align: top;
}

.quote::after {
    content: """;
    font-size: 2em;
    color: #007bff;
    vertical-align: bottom;
}

/* 图标和装饰 */
.email::before {
    content: "✉ ";
    color: #6c757d;
}

.phone::before {
    content: " ";
    color: #28a745;
}

/* 清除浮动 */
.clearfix::after {
    content: "";
    display: table;
    clear: both;
}

/* 工具提示 */
.tooltip {
    position: relative;
}

.tooltip::after {
    content: attr(data-tooltip);
    position: absolute;
    bottom: 100%;
    left: 50%;
    transform: translateX(-50%);
    background-color: #333;
    color: white;
    padding: 5px 10px;
    border-radius: 4px;
    white-space: nowrap;
    opacity: 0;
    pointer-events: none;
    transition: opacity 0.3s;
}

.tooltip:hover::after {
    opacity: 1;
}
6.1.2 ::first-line和::first-letter
/* 首行样式 */
p::first-line {
    font-weight: bold;
    color: #007bff;
    text-transform: uppercase;
}

/* 首字母样式(下沉式大写字母) */
.article::first-letter {
    font-size: 3em;
    float: left;
    line-height: 1;
    margin: 0 8px 0 0;
    color: #dc3545;
    font-weight: bold;
}

6.2 高级伪元素应用

6.2.1 装饰和图形
/* 分隔线 */
.divider::before {
    content: "";
    display: block;
    width: 50px;
    height: 2px;
    background-color: #007bff;
    margin: 20px auto;
}

/* 角标 */
.badge {
    position: relative;
}

.badge::after {
    content: attr(data-count);
    position: absolute;
    top: -8px;
    right: -8px;
    background-color: #dc3545;
    color: white;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    font-size: 12px;
    text-align: center;
    line-height: 20px;
}

/* 三角形指示器 */
.arrow-right::after {
    content: "";
    width: 0;
    height: 0;
    border-left: 10px solid #007bff;
    border-top: 5px solid transparent;
    border-bottom: 5px solid transparent;
    display: inline-block;
    margin-left: 5px;
}

7. 选择器优先级

7.1 优先级计算规则

/* 优先级权重(从高到低):
   1. 内联样式:1000
   2. ID选择器:100
   3. 类选择器、属性选择器、伪类:10
   4. 元素选择器、伪元素:1
   5. 通用选择器:0
*/

/* 示例优先级计算: */

/* 权重:1 */
p { color: black; }

/* 权重:10 */
.text { color: blue; }

/* 权重:11 (10+1) */
p.text { color: green; }

/* 权重:100 */
#content { color: red; }

/* 权重:111 (100+10+1) */
#content .text p { color: purple; }

/* !important 会覆盖其他所有规则 */
p { color: orange !important; }

7.2 优先级最佳实践

/* ✅ 推荐:使用较低特异性,便于维护 */
.button { 
    background: blue; 
}

.button-primary { 
    background: green; 
}

/* ❌ 避免:过高特异性 */
div.container #sidebar ul.nav li.item a.link {
    color: red;
}

/* ✅ 更好的方式 */
.nav-link {
    color: red;
}

/* ❌ 避免:过度使用!important */
.text {
    color: blue !important;
    font-size: 16px !important;
}

/* ✅ 更好的结构化方式 */
.text-primary {
    color: blue;
    font-size: 16px;
}

8. 性能优化

8.1 高效选择器编写

/* ✅ 高效:ID选择器 */
#header { }

/* ✅ 高效:类选择器 */
.navigation { }

/* ⚠️ 中等:属性选择器 */
input[type="text"] { }

/* ❌ 低效:通用选择器 */
* { }

/* ❌ 低效:复杂的后代选择器 */
div > ul > li > a:hover { }

/* ✅ 更好:使用类名 */
.nav-link:hover { }

8.2 选择器优化建议

/* 1. 避免过深的嵌套 */
/* ❌ 不推荐 */
.sidebar .widget .title .text .link { }

/* ✅ 推荐 */
.widget-link { }

/* 2. 优先使用类选择器 */
/* ❌ 低效 */
div[data-type="widget"] ul li:first-child { }

/* ✅ 高效 */
.widget-first-item { }

/* 3. 避免不必要的限定符 */
/* ❌ 多余 */
div.container { }
ul.nav { }

/* ✅ 简洁 */
.container { }
.nav { }

9. 实际应用场景

9.1 响应式导航菜单

.nav {
    display: flex;
    list-style: none;
    margin: 0;
    padding: 0;
}

.nav > li {
    position: relative;
}

.nav > li > a {
    display: block;
    padding: 15px 20px;
    text-decoration: none;
    color: #333;
    transition: background-color 0.3s;
}

.nav > li:hover > a {
    background-color: #f8f9fa;
}

/* 下拉菜单 */
.nav > li > ul {
    position: absolute;
    top: 100%;
    left: 0;
    background: white;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    opacity: 0;
    visibility: hidden;
    transition: all 0.3s;
}

.nav > li:hover > ul {
    opacity: 1;
    visibility: visible;
}

/* 移动端适配 */
@media (max-width: 768px) {
    .nav {
        flex-direction: column;
    }
    
    .nav > li > ul {
        position: static;
        box-shadow: none;
        opacity: 1;
        visibility: visible;
        max-height: 0;
        overflow: hidden;
        transition: max-height 0.3s;
    }
    
    .nav > li:hover > ul {
        max-height: 200px;
    }
}

9.2 表单验证样式

.form-group {
    margin-bottom: 20px;
    position: relative;
}

.form-control {
    width: 100%;
    padding: 12px;
    border: 2px solid #ddd;
    border-radius: 4px;
    transition: border-color 0.3s;
}

/* 验证状态 */
.form-control:focus {
    border-color: #007bff;
    outline: none;
}

.form-control:valid {
    border-color: #28a745;
}

.form-control:invalid:not(:focus):not(:placeholder-shown) {
    border-color: #dc3545;
}

/* 验证图标 */
.form-control:valid + .validation-icon::after {
    content: "✓";
    color: #28a745;
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%);
}

.form-control:invalid:not(:focus):not(:placeholder-shown) + .validation-icon::after {
    content: "✕";
    color: #dc3545;
    position: absolute;
    right: 12px;
    top: 50%;
    transform: translateY(-50%);
}

10. 最佳实践

10.1 选择器命名规范

/* BEM命名方法论 */
.block { }
.block__element { }
.block--modifier { }

/* 示例 */
.card { }
.card__header { }
.card__body { }
.card__footer { }
.card--large { }
.card--primary { }

/* 状态类 */
.is-active { }
.is-hidden { }
.is-loading { }

/* 工具类 */
.text-center { }
.margin-bottom-lg { }
.display-none { }

10.2 选择器组织结构

/* 1. 基础重置 */
* { box-sizing: border-box; }

/* 2. 元素选择器 */
body { font-family: Arial, sans-serif; }
h1, h2, h3 { margin-top: 0; }

/* 3. 类选择器(按组件分组) */
.header { }
.navigation { }
.content { }
.sidebar { }
.footer { }

/* 4. 状态类 */
.is-active { }
.is-disabled { }

/* 5. 工具类 */
.text-center { }
.margin-auto { }

/* 6. 响应式 */
@media (min-width: 768px) { }

11. 常见问题

11.1 选择器问题排查

/* 问题1:样式不生效 */
/* 检查优先级 */
.button { color: blue; }          /* 权重:10 */
#header .button { color: red; }   /* 权重:110,会覆盖上面的样式 */

/* 问题2:继承问题 */
.parent { color: blue; }
.parent .child { }  /* 子元素会继承父元素的颜色 */

/* 问题3:伪类顺序 */
/* 正确的顺序:LVHA */
a:link { }
a:visited { }
a:hover { }
a:active { }

11.2 兼容性注意事项

/* 伪元素兼容性 */
/* CSS2语法(兼容旧浏览器) */
.element:before { content: ""; }
.element:after { content: ""; }

/* CSS3语法(推荐) */
.element::before { content: ""; }
.element::after { content: ""; }

/* 属性选择器兼容性 */
/* IE6+支持 */
input[type="text"] { }

/* IE7+支持 */
input[type^="text"] { }
input[type$="text"] { }
input[type*="text"] { }

12. 总结

12.1 选择器使用建议

  1. 优先使用类选择器:性能好,维护性强
  2. 避免过深嵌套:保持选择器简洁
  3. 合理使用伪类:提升用户体验
  4. 遵循命名规范:提高代码可读性
  5. 注意浏览器兼容性:确保跨浏览器一致性

12.2 学习建议

  1. 循序渐进:从基本选择器开始学习
  2. 多做练习:通过实际项目应用知识
  3. 关注性能:选择合适的选择器提高性能
  4. 持续学习:关注CSS新特性和最佳实践

你可能感兴趣的:(css,前端)