CSS 选择符与继承属性

CSS 选择器类型、优先级及可继承属性总结

问题

CSS 选择符有哪些?哪些属性可以继承?

解答

CSS 选择符

/* 1. id 选择器 */
#header { color: red; }

/* 2. 类选择器 */
.container { width: 100%; }

/* 3. 标签选择器 */
div { margin: 0; }

/* 4. 后代选择器(空格) */
div p { color: blue; }

/* 5. 子选择器(>) */
div > p { color: green; }

/* 6. 相邻兄弟选择器(+) */
h1 + p { margin-top: 0; }

/* 7. 通用兄弟选择器(~) */
h1 ~ p { color: gray; }

/* 8. 通配符选择器 */
* { box-sizing: border-box; }

/* 9. 属性选择器 */
input[type="text"] { border: 1px solid #ccc; }
a[href^="https"] { color: green; }  /* 以 https 开头 */
a[href$=".pdf"] { color: red; }     /* 以 .pdf 结尾 */
a[href*="example"] { color: blue; } /* 包含 example */

/* 10. 伪类选择器 */
a:hover { text-decoration: underline; }
li:first-child { font-weight: bold; }
li:nth-child(2n) { background: #f5f5f5; }

/* 11. 伪元素选择器 */
p::before { content: "→ "; }
p::after { content: " ←"; }
p::first-line { font-weight: bold; }

选择器优先级

从高到低排列:

选择器权重
!important最高
内联样式1000
id 选择器100
类/伪类/属性选择器10
标签/伪元素选择器1
通配符/子选择器/相邻选择器0

可继承属性

/* 字体相关 - 可继承 */
font-family
font-size
font-weight
font-style

/* 文本相关 - 可继承 */
color
text-align
text-indent
line-height
letter-spacing
word-spacing
white-space

/* 列表相关 - 可继承 */
list-style
list-style-type
list-style-position

/* 其他可继承 */
visibility
cursor

不可继承属性

/* 盒模型 - 不可继承 */
width, height
margin, padding
border

/* 定位 - 不可继承 */
position
top, right, bottom, left
float, clear

/* 背景 - 不可继承 */
background
background-color
background-image

/* 显示 - 不可继承 */
display
overflow

强制继承

.child {
  /* 强制继承父元素的值 */
  border: inherit;
  
  /* 重置为初始值 */
  color: initial;
  
  /* 如果可继承则继承,否则用初始值 */
  margin: unset;
}

关键点

  • 选择器优先级:!important > 内联 > id > class > 标签
  • 字体、文本、颜色相关属性通常可继承
  • 盒模型、定位、背景相关属性不可继承
  • 使用 inheritinitialunset 可控制继承行为
  • 优先级相同时,后定义的样式覆盖先定义的