You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS子元素继承百分比而非计算值的问题咨询

关于CSS padding: inherit 的继承逻辑问题

问题代码

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {
            width: 1000px;
        }
        article {
            padding: 10%;
        }
        section {
            padding: inherit;
        }
    </style>
</head>
<body>
    <article>
        <section>
            <p>Hello world</p>
        </section>
    </article>
<script>
    const section = document.querySelector("section");
    const style = getComputedStyle(section);
    console.log(style.paddingTop); 
</script>
</body>
</html>

问题解析

  • 核心原因是CSS中带百分比单位的属性,inherit继承的是声明的百分比值,而非父元素计算后的像素结果。
  • article的padding:10%基于父元素body的宽度(1000px)计算出100px内边距,但这个计算后的数值不会被继承。
  • section通过padding: inherit拿到的是10%这个原始声明值,它会基于自己的直接父元素(article)的内容宽度重新计算:article的内容宽度为1000px - 2*10%*1000px = 800px,因此section的10% padding最终计算为800px * 10% = 80px。

解决方法

如果想让section继承article计算后的100px内边距,可采用以下两种方案:

  • 给article添加box-sizing: border-box,使article的width:1000px包含padding,其内容宽度保持1000px,此时section的10% padding会直接计算为100px:
    article {
        padding: 10%;
        box-sizing: border-box;
    }
    
  • 改用CSS变量传递计算逻辑,直接基于body宽度计算固定值:
    article {
        --base-padding: 10%;
        padding: var(--base-padding);
    }
    section {
        padding: calc(1000px * var(--base-padding));
    }
    

内容的提问来源于stack exchange,提问作者Paul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 00:58:24