CSS3 属性选择器

CSS3 对属性选择器进行了显著的增强,提供了更强大的属性匹配能力。这些增强的选择器让我们能够基于属性的值进行更精确的元素选择,大大提高了样式控制的灵活性和精确度。

属性选择器概述

属性选择器允许我们根据元素的属性及其值来选择元素。CSS3 在原有属性选择器的基础上,增加了几种新的匹配方式,使得属性选择器变得更加强大和灵活。

基本属性选择器回顾

在介绍 CSS3 新增的属性选择器之前,先回顾一下基本的属性选择器:

/* 存在指定属性 */
a[href] {
  color: blue;
}

/* 属性值完全匹配 */
input[type="text"] {
  width: 200px;
}

/* 属性值包含特定单词(用空格分隔) */
a[href~="example"] {
  color: green;
}

CSS3 新增的属性选择器

1. [attr^=value] - 以值开头

这个选择器匹配属性值以指定字符串开头的元素。

/* 选择 href 属性以 "https://" 开头的链接 */
a[href^="https://"] {
  color: green;
}

/* 选择 class 属性以 "btn-" 开头的元素 */
div[class^="btn-"] {
  display: inline-block;
  padding: 10px 20px;
}

/* 选择 src 属性以 "http://" 开头的图片 */
img[src^="http://"] {
  border: 1px solid #ddd;
}

实际应用场景:

  • 区分安全链接:将 HTTPS 链接标记为安全
  • 识别特定类名模式:选择具有特定前缀的类名
  • 过滤外部资源:区分本地和外部资源
/* 实际示例:安全链接样式 */
a[href^="https://"] {
  color: #28a745;
}

a[href^="https://"]::before {
  content: "🔒 ";
  margin-right: 3px;
}

/* 外部链接警告 */
a[href^="http://"]::after {
  content: " ⚠️";
  color: #ffc107;
}

2. [attr$=value] - 以值结尾

这个选择器匹配属性值以指定字符串结尾的元素。

/* 选择 href 属性以 ".pdf" 结尾的链接 */
a[href$=".pdf"] {
  color: red;
}

/* 选择 src 属性以 ".png" 结尾的图片 */
img[src$=".png"] {
  border: 1px solid #007bff;
}

/* 选择 href 属性以 "/" 结尾的链接 */
a[href$="/"] {
  font-weight: bold;
}

实际应用场景:

  • 文件类型识别:根据文件扩展名设置不同样式
  • 链接类型区分:识别特定类型的链接
  • 资源过滤:选择特定类型的资源
/* 实际示例:文件类型图标 */
a[href$=".pdf"]::before {
  content: "📄 ";
}

a[href$=".doc"]::before,
a[href$=".docx"]::before {
  content: "📝 ";
}

a[href$=".xls"]::before,
a[href$=".xlsx"]::before {
  content: "📊 ";
}

a[href$=".zip"]::before,
a[href$=".rar"]::before {
  content: "📦 ";
}

/* 下载链接样式 */
a[href$=".pdf"],
a[href$=".zip"],
a[href$=".rar"] {
  background: #f8f9fa;
  padding: 2px 6px;
  border-radius: 3px;
  border: 1px solid #dee2e6;
}

3. [attr*=value] - 包含值

这个选择器匹配属性值包含指定字符串的元素。

/* 选择 title 属性包含 "CSS" 的元素 */
*[title*="CSS"] {
  border: 1px solid #007bff;
}

/* 选择 href 属性包含 "example" 的链接 */
a[href*="example"] {
  color: purple;
}

/* 选择 class 属性包含 "active" 的元素 */
div[class*="active"] {
  background: #28a745;
  color: white;
}

实际应用场景:

  • 关键词搜索:选择包含特定关键词的元素
  • 类名模式匹配:选择包含特定字符串的类名
  • 内容过滤:基于属性内容进行过滤
/* 实际示例:高亮包含特定关键词的元素 */
*[title*="重要"] {
  border-left: 3px solid #dc3545;
  padding-left: 10px;
}

/* 搜索结果高亮 */
.search-result[*data-content*="搜索词"] {
  background: #fff3cd;
}

/* 表单验证提示 */
input[placeholder*="必填"] + .error-message {
  display: block;
}

4. [attr~=value] - 包含单词

这个选择器匹配属性值包含指定单词的元素(单词用空格分隔)。

/* 选择 class 属性包含 "button" 单词的元素 */
button[class~="button"] {
  padding: 10px 20px;
}

/* 选择 title 属性包含 "warning" 单词的元素 */
div[title~="warning"] {
  background: #ffc107;
}

/* 选择 data-tags 属性包含 "featured" 单词的元素 */
article[data-tags~="featured"] {
  border: 2px solid #007bff;
}

实际应用场景:

  • 多类名选择:选择具有特定类名的元素
  • 标签系统:基于标签选择元素
  • 属性值分割:处理空格分隔的属性值
/* 实际示例:按钮样式 */
button[class~="primary"] {
  background: #007bff;
  color: white;
}

button[class~="secondary"] {
  background: #6c757d;
  color: white;
}

button[class~="danger"] {
  background: #dc3545;
  color: white;
}

/* 文章标签 */
article[data-tags~="javascript"] {
  border-left: 3px solid #f7df1e;
}

article[data-tags~="css"] {
  border-left: 3px solid #264de4;
}

article[data-tags~="html"] {
  border-left: 3px solid #e34c26;
}

5. [attr|=value] - 以值开头或值-开头

这个选择器匹配属性值以指定字符串开头,或以指定字符串加连字符开头的元素。

/* 选择 lang 属性以 "zh" 开头的元素 */
div[lang|="zh"] {
  font-family: "Microsoft YaHei", sans-serif;
}

/* 选择 href 属性以 "/docs/" 开头的链接 */
a[href|="/docs/"] {
  color: #007bff;
}

/* 选择 data-category 属性以 "tech-" 开头的元素 */
article[data-category|="tech-"] {
  background: #e3f2fd;
}

实际应用场景:

  • 语言选择:根据语言代码选择元素
  • 路径匹配:匹配特定路径下的元素
  • 分类系统:基于分类前缀选择元素
/* 实际示例:语言字体设置 */
html[lang|="zh"] {
  font-family: "Microsoft YaHei", "PingFang SC", sans-serif;
}

html[lang|="en"] {
  font-family: Arial, Helvetica, sans-serif;
}

html[lang|="ja"] {
  font-family: "Hiragino Kaku Gothic Pro", "Meiryo", sans-serif;
}

/* 文档导航 */
nav a[href|="/docs/"] {
  font-weight: bold;
  color: #007bff;
}

/* 产品分类 */
.product[data-category|="electronics-"] {
  border: 1px solid #007bff;
}

.product[data-category|="clothing-"] {
  border: 1px solid #28a745;
}

属性选择器的组合使用

CSS3 允许我们组合使用多个属性选择器,创建更精确的选择规则。

/* 组合多个属性选择器 */
a[href^="https://"][target="_blank"] {
  color: #28a745;
}

a[href^="https://"][target="_blank"]::after {
  content: " ↗";
}

/* 复杂组合 */
input[type="text"][placeholder*="email"][required] {
  border: 2px solid #007bff;
}

/* 否定选择器组合 */
a:not([href^="http://"]):not([href^="https://"]) {
  color: #6c757d;
}

实际应用案例

1. 外部链接标识

/* 识别外部链接 */
a[href^="http://"]:not([href*="example.com"]),
a[href^="https://"]:not([href*="example.com"]) {
  color: #007bff;
}

a[href^="http://"]:not([href*="example.com"])::after,
a[href^="https://"]:not([href*="example.com"])::after {
  content: " ↗";
  font-size: 0.8em;
  color: #007bff;
}

2. 文件下载链接

/* 下载文件链接 */
a[href$=".pdf"],
a[href$=".doc"],
a[href$=".docx"],
a[href$=".xls"],
a[href$=".xlsx"],
a[href$=".zip"],
a[href$=".rar"] {
  display: inline-flex;
  align-items: center;
  padding: 4px 8px;
  background: #f8f9fa;
  border: 1px solid #dee2e6;
  border-radius: 4px;
  text-decoration: none;
  color: #333;
}

a[href$=".pdf"]::before {
  content: "📄";
  margin-right: 5px;
}

a[href$=".doc"]::before,
a[href$=".docx"]::before {
  content: "📝";
  margin-right: 5px;
}

a[href$=".xls"]::before,
a[href$=".xlsx"]::before {
  content: "📊";
  margin-right: 5px;
}

a[href$=".zip"]::before,
a[href$=".rar"]::before {
  content: "📦";
  margin-right: 5px;
}

3. 表单验证样式

/* 必填字段 */
input[required],
textarea[required],
select[required] {
  border-left: 3px solid #dc3545;
}

input[required]::placeholder,
textarea[required]::placeholder {
  color: #dc3545;
}

/* 邮箱字段 */
input[type="email"] {
  background: url('email-icon.png') no-repeat right 10px center;
}

/* 密码字段 */
input[type="password"] {
  background: url('lock-icon.png') no-repeat right 10px center;
}

/* 特定占位符 */
input[placeholder*="必填"] {
  border: 2px solid #dc3545;
}

input[placeholder*="可选"] {
  border: 2px solid #6c757d;
}

4. 图片处理

/* SVG 图片 */
img[src$=".svg"] {
  width: 100%;
  height: auto;
}

/* 透明图片 */
img[src*="transparent"],
img[src*="alpha"] {
  background:
    linear-gradient(45deg, #ccc 25%, transparent 25%),
    linear-gradient(-45deg, #ccc 25%, transparent 25%),
    linear-gradient(45deg, transparent 75%, #ccc 75%),
    linear-gradient(-45deg, transparent 75%, #ccc 75%);
  background-size: 20px 20px;
  background-position: 0 0, 0 10px, 10px -10px, -10px 0px;
}

/* 头像图片 */
img[src*="avatar"],
img[src*="profile"] {
  border-radius: 50%;
  object-fit: cover;
}

5. 社交媒体链接

/* 社交媒体链接 */
a[href*="facebook.com"] {
  color: #1877f2;
}

a[href*="twitter.com"] {
  color: #1da1f2;
}

a[href*="linkedin.com"] {
  color: #0077b5;
}

a[href*="github.com"] {
  color: #333;
}

a[href*="youtube.com"] {
  color: #ff0000;
}

/* 社交媒体图标 */
a[href*="facebook.com"]::before {
  content: "📘";
}

a[href*="twitter.com"]::before {
  content: "🐦";
}

a[href*="linkedin.com"]::before {
  content: "💼";
}

a[href*="github.com"]::before {
  content: "🐙";
}

属性选择器的性能考虑

虽然属性选择器非常强大,但在使用时也需要考虑性能问题:

1. 避免过度使用

/* 不推荐 - 过于复杂 */
div[data-category*="tech"][data-status="active"][data-featured="true"] {
  /* 样式 */
}

/* 推荐 - 使用类名 */
.featured-tech-item {
  /* 样式 */
}

2. 选择器优化

/* 推荐 - 更具体的选择器 */
a[href^="https://"] {
  /* 样式 */
}

/* 不推荐 - 过于宽泛 */
[href^="https://"] {
  /* 样式 */
}

3. 缓存选择器

/* 推荐 - 使用类名 */
.external-link {
  /* 样式 */
}

/* 不推荐 - 每次都计算属性选择器 */
a[href^="http://"]:not([href*="example.com"]) {
  /* 样式 */
}

总结

CSS3 的属性选择器增强为我们提供了强大的元素选择能力:

  1. [attr^=value]:匹配以指定字符串开头的属性值
  2. [attr$=value]:匹配以指定字符串结尾的属性值
  3. *[attr=value]**:匹配包含指定字符串的属性值
  4. [attr~=value]:匹配包含指定单词的属性值
  5. [attr|=value]:匹配以指定字符串或以指定字符串加连字符开头的属性值

实际应用场景:

  • 链接分类:区分不同类型的链接
  • 文件识别:根据文件扩展名设置样式
  • 表单样式:基于表单属性设置样式
  • 多媒体处理:根据资源类型设置样式
  • 社交媒体:识别不同的社交媒体链接

最佳实践:

  • 合理使用:根据实际需求选择合适的选择器
  • 性能优化:避免过度复杂的选择器
  • 代码维护:保持选择器的可读性和可维护性
  • 浏览器兼容:注意不同浏览器的兼容性

掌握这些增强的属性选择器,能够让我们更精确地控制元素样式,创建更加灵活和强大的样式规则。在接下来的章节中,我们将学习 CSS3 的其他高级选择器。