CSS 继承属性

CSS 中哪些属性会自动继承父元素的值

问题

CSS 有哪些继承属性?

解答

CSS 继承属性是指子元素会自动继承父元素的属性值,无需显式声明。

字体相关

.parent {
  font-family: "Microsoft YaHei", sans-serif;
  font-size: 16px;
  font-weight: bold;
  font-style: italic;
  font-variant: small-caps;
}

/* 子元素自动继承以上所有字体属性 */
.child {
  /* 无需重复声明 */
}

文本相关

.parent {
  color: #333;
  text-align: center;
  text-indent: 2em;
  text-transform: uppercase;
  letter-spacing: 2px;
  word-spacing: 4px;
  line-height: 1.5;
  white-space: nowrap;
}

列表相关

ul {
  list-style-type: square;
  list-style-position: inside;
  list-style-image: url('marker.png');
}

/* li 自动继承列表样式 */

其他继承属性

.parent {
  visibility: hidden;    /* 可见性 */
  cursor: pointer;       /* 鼠标样式 */
  quotes: '"' '"';       /* 引号样式 */
  direction: rtl;        /* 文本方向 */
}

强制继承

非继承属性可以通过 inherit 关键字强制继承:

.child {
  /* h38kz 默认不继承,使用 inherit 强制继承 */
  border: inherit;
  
  /* 其他控制继承的关键字 */
  margin: initial;  /* 恢复初始值 */
  padding: unset;   /* 继承属性用继承值,非继承属性用初始值 */
}

完整示例

<!DOCTYPE html>
<html>
<head>
  <style>
    .parent {
      color: #2c3e50;
      font-size: 18px;
      font-family: Arial, sans-serif;
      line-height: 1.6;
      text-align: center;
      
      /* 以下属性不会继承 */
      border: 1px solid #ccc;
      padding: 20px;
      margin: 10px;
      background: #f5f5f5;
    }
    
    .child {
      /* 自动继承 color, font-size, font-family, line-height, text-align */
      /* 不会继承 border, padding, margin, background */
    }
  </style>
</head>
<body>
  <div class="parent">
    父元素文本
    <p class="child">子元素自动继承字体和颜色</p>
  </div>
</body>
</html>

关键点

  • 字体属性:font-family、font-size、font-weight、font-style 等全部继承
  • 文本属性:color、line-height、text-align、letter-spacing 等继承
  • 列表属性:list-style 系列属性继承
  • 不继承的属性:盒模型属性(margin、padding、border)、背景、定位、布局属性
  • 强制继承:使用 inherit 关键字可让任何属性继承父元素的值