CSS 属性继承指南

101 阅读1分钟

CSS 属性可以分为两大类:继承属性和非继承属性。

会继承的属性

通常,与文字排版相关的属性会被继承:

  1. 字体相关:

    • font-family
    • font-size
    • font-style
    • font-weight
    • font-variant
  2. 文本相关:

    • text-align
    • text-indent
    • text-transform
    • letter-spacing
    • word-spacing
    • line-height
    • color
  3. 列表相关:

    • list-style
    • list-style-type
    • list-style-position
  4. 其他:

    • visibility
    • cursor

不会继承的属性

通常,与布局相关的属性不会被继承:

  1. 盒模型相关:

    • width, height
    • margin, padding
    • border
  2. 定位相关:

    • position
    • top, right, bottom, left
    • z-index
  3. 背景相关:

    • background, background-color, background-image
  4. 布局相关:

    • display
    • float
    • clear
  5. 其他:

    • opacity
    • box-shadow
    • transform

特殊情况

  1. inherit 关键字:

    • 可以用于任何 CSS 属性。
    • 强制继承父元素的对应属性值。
  2. 默认值:

    • 一些属性虽然不继承,但有默认值可能与继承相似。
    • 例如:border-color 默认值是元素的 color
  3. 根元素:

    • 一些属性在根元素(通常是 <html>)上有特殊的默认值。
    • 例如:color 默认为黑色,font-size 默认为中等大小。

注意事项

  • 继承是从父元素到子元素的,不会反向传递。
  • 某些属性的继承可能会被覆盖,比如浏览器的用户代理样式表。
  • 在使用 CSS 框架时,要注意框架可能会改变某些元素的默认继承行为。