首页 > 解决方案 > 父级的 100% 宽度不采用边框宽度

问题描述

.item {
    box-sizing: border-box;
    width: 500px;
    height: 60px;
    background-color: blue;
    border: 20px solid red;
    padding: 10px;
    position: relative;
}

.child {
    width: 100%;
    background-color: yellow;
    height: 100%;
    box-sizing: border-box;
    position: absolute;
    top: 0;
    left: 0;

}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div class="item">
        <div class="child">

        </div>
    </div>
</body>
</html>

编辑:

来自:https ://www.w3.org/TR/CSS22/visudet.html#the-width-property :

对于包含块基于块容器元素的绝对定位元素,百分比是根据该元素的填充框的宽度计算的。这是从 CSS1 的一个变化,其中百分比宽度总是相对于父元素的内容框计算。

为什么会这样?我正在使用边框框,期望我得到包括边框在内的父容器宽度的 100%。有谁知道也包括边界的方法?

.child元素设置100%为父元素的宽度(由于 box-sizing:border-box 属性,其宽度是内容 + 填充 + 边框的总和),但仅考虑内容 + 填充。为什么不走边界?我知道当我使用 top/left/bottom/right 属性时,定位是相对于元素的填充边缘,但是当它设置为时,孩子不应该尊重边框的宽度100%吗?

标签: css

解决方案


发生这种情况是因为该属性width被明确定义为相对于content-box(默认)。将父级设置box-sizingborder-box不会改变这种行为。

我相信克服这个问题的方法是使用outline属性来使边界不占用空间。

请参阅下面的可能替代方案:

<!DOCTYPE html>
<html lang="en">
<style>

.item {

    width: 500px;
    height: 60px;
    background-color: blue;
    outline:20px solid red;
    border:1px solid black;
    padding: 10px;
    position: relative;
}

.child {
    width: 100%;
    background-color: yellow;
    height: 100%;

    outline:1px solid yellow;
    position: absolute;
    top: 0;
    left: 0;

}

</style>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div class="item">
        <div class="child">

        </div>
    </div>
</body>
</html>

推荐阅读