Skip to content

CSS Selector 不 Matching

快速摘要

你的 CSS 规则有 否副作用因为 selector doesn't match 任何元素 — or 更多特定规则 overrides 它 in cascade.

为什么发生

  • Typo in 类 or id name in CSS selector

  • Another 规则使用 higher specificity overrides 你的规则

  • 元素 doesn't 有类 or id 你're targeting

最小示例

✗ 错误代码
.buton {
  color: red;
}
✓ 修复代码
.button {
  color: red;
}

类是 spelled .buton in CSS 但 HTML 元素有 类="button" — fix typo 所以 selector matches.

如何诊断

  • Use DevTools 到 inspect 元素 and 检查哪个规则是 applied

  • Look for overridden 规则 (struck-通过样式) in 样式 panel

  • 验证 selector matches 通过测试它 in 浏览器 console 使用 document.querySelectorAll

如何修复

  • Fix selector spelling 到 match 元素's 类 or id

  • Increase specificity or reorder 规则如果 cascade 是 overriding

  • 添加正确类 or id 到 HTML 元素

如何预防

  • Use DevTools inspector regularly 到验证样式是 applied

  • Follow consistent naming 约定 (e.g., BEM) 到 avoid specificity wars

相关资源

相关课程

  • CSS

    学习 CSS 基本

相关练习

← 返回语言