为什么 CSS width: calc(inherit) 做的事情与 width: inherit 不同?

Why does CSS width: calc(inherit) do something different than width: inherit?

我是一名正在尝试 CSS 和 HTML 的中学生,我注意到 width: calc(inherit) 的作用与 width: inherit 不同。

下面的片段是什么宽度:inherit;

.header {
 background-color: #77a4ed;
 min-width: 200px;
 width: fit-content;
 border-top-left-radius: 50px;
 border-top-right-radius: 50px;
 height: 30px;
 text-align: center;
 height: 20px;
}

.header > div {
 background-color: whitesmoke;
 border-right: solid 2px black;
 border-left: solid 2px black;
 border-top: solid 2px black;
 min-width: 200px;
 width: inherit;
 text-align: center;
 margin: auto;
 padding-left: 10px;
 padding-right: 10px;
 padding-top: 3px;
 padding-bottom: 3px;
}

.header > div:last-of-type {
 background-color: whitesmoke;
 border-right: solid 2px black;
 border-left: solid 2px black;
 min-width: 200px;
 width: fit-content;
 margin: auto;
 padding-left: 10px;
 border-bottom: solid 2px black;
 border-bottom-left-radius: 10px;
 border-bottom-right-radius: 10px;
}
<div class='container'>
<div class='header'>
&nbsp;
<div>
test
</div>
<div>
test..........................................................
</div>
</div>
</div>

这段代码是什么宽度:calc(inherit);

.header {
 background-color: #77a4ed;
 min-width: 200px;
 width: fit-content;
 border-top-left-radius: 50px;
 border-top-right-radius: 50px;
 height: 30px;
 text-align: center;
 height: 20px;
}

.header > div {
 background-color: whitesmoke;
 border-right: solid 2px black;
 border-left: solid 2px black;
 border-top: solid 2px black;
 min-width: 200px;
 width: calc(inherit);
 text-align: center;
 margin: auto;
 padding-left: 10px;
 padding-right: 10px;
 padding-top: 3px;
 padding-bottom: 3px;
}

.header > div:last-of-type {
 background-color: whitesmoke;
 border-right: solid 2px black;
 border-left: solid 2px black;
 min-width: 200px;
 width: fit-content;
 margin: auto;
 padding-left: 10px;
 border-bottom: solid 2px black;
 border-bottom-left-radius: 10px;
 border-bottom-right-radius: 10px;
}
<div class='container'>
    <div class='header'>
    &nbsp;
    <div>
    test
    </div>
    <div>
    test..........................................................
    </div>
    </div>
    </div>

我不明白为什么他们会给出不同的结果。有人可以解释一下吗?

如果您检查 console.log,您会发现 calc 不适用于继承。

#a1{
width:inherit;
}

#a2{
width: calc (inherit);
}
<div id='a1'>xxx</div>
<div id='a2'>xxx</div>

calc() 假设使用 -、+、* 或 / 等数学表达式进行计算 示例

width: calc(100% - 100px); 

你没有任何表达式,所以它可能无效,但也许如果你使 .header 宽度有一个表达式,然后使用可能有效的继承

.header{
    width: cal(100% - 100px);
}
.header{
    width: inherit;
}

这可能有效,但也不确定我不知道 100% - 100px 是否是您要寻找的确切宽度

只需使用width: 100%,它将占据父元素的整个宽度。