The difference between inherit and initial in css


foreword

First let us understand what these two words mean from an English perspective?
inherit:继承
initial:最初的、开始的

One, inherit (inheritance)

1: Definition

The inherit keyword specifies that an attribute should inherit its value from the parent element.

2: Usage

The inherit keyword can be used with any CSS property on any HTML element.

3: Example

3.1 Code
 span {
    
    
   color: blue;
    border:1px solid black;
}
.extend span  {
    
    
    color: inherit;
}
<div>
 这里是一个蓝色的 <span>span 元素</span>,正如 span 元素所设置的。
</div>
<div class="extend" style="color:red">
  这里是一个绿色的 <span>span 元素</span>,因为它继承了父元素。
</div>
<div class="extend">
  这里是一个黑色的 <span>span 元素</span>,因为它继承了父元素并且父元素没有颜色。
</div>
<div style="color:green">
  这里是一个蓝色的 <span>span 元素</span>,正如 span 元素所设置的。
</div>
3.2 Renderings

insert image description here

3.3 Description

As shown in the effect diagram of the above example,第二行和第三行都使用了inherit 来继承父元素的颜色属性,第二行有红色,第三行没有(继承了寂寞),显示了上图效果。

2. Use steps

1: Definition

The initial keyword is used to set a CSS property to its default value.

2: Usage

The initial keyword can be used with any CSS property on any HTML element.

3: Example

3.1 Code
div {
    
    
  color: red; 
}
h1 {
    
    
  color: initial; 
}
<div>
  <h1>Initial</h1>
  <p>div 元素内的标题和文本的 color 属性被设置为 "red"。标题元素的 color 属性被另外设置为 "initial",因此是这里是红色,标题是默认的黑色</p>
</div>
3.2 Renderings

insert image description here

3.3 Description

Example above:div 元素内的标题和文本的 color 属性被设置为 "red"。标题元素的 color 属性被另外设置为 "initial",因此是这里是黑色,标题是红色

Summary: The difference between inherit and initial

同:inherit和initial这两个关键字可用于任何 HTML 元素上的任何 CSS 属性。
异:inherit是继承,initial 是恢复最初值。

Reference article:

inheritw3c official explanation: http://www.w3cmap.com/cssref/css-inherit.html
initialw3c official explanation: http://www.w3cmap.com/cssref/css-initial.html

Guess you like

Origin blog.csdn.net/weixin_44784401/article/details/130043400