.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不同,CSS1中百分比宽度总是相对于父元素的内容框计算。
为什么会这样呢?我正在使用border-box属性,期望得到包括边框在内的父容器的100%宽度。有人知道如何同时包括边框吗?
.child
元素设置为父元素(因为具有box-sizing:border-box属性,其宽度等于内容+填充+边框的总和)的100%宽度,但仅考虑内容+填充。为什么不考虑边框呢?我知道当我使用top/left/bottom/right属性时,位置是相对于元素的填充边缘计算的,但如果将子元素设置为100%,难道不应该同时考虑边框的宽度吗?