我想将 header
的宽度设置为 conatiner
宽度,同时考虑到 header
的边距
div.container {
width: 100%;
height: 300px;
border: 1px solid red;
position:relative;
}
header{
width: 100%;
border: 1px solid green;
height: 20px;
margin: 10px;
}
<div class="container">
<header></header>
</div>
但是 header
元素在右侧的几个像素处脱离了容器的边界。
还尝试将 box-sizing: border-box;
添加到 header
的样式中,但没有任何反应。为什么?
最佳答案
为 header
设置 width: calc(100% - 22px);
。即 100% 减去两倍边框 (2 * 1px) 减去两倍边距 (2*10px),总计为 22px。
div.container {
width: 100%;
height: 300px;
border: 1px solid red;
position:relative;
}
header{
width: calc(100% - 22px);
border: 1px solid green;
height: 20px;
margin: 10px;
}
<div class="container">
<header></header>
</div>
关于html - 在存在边距的情况下设置子项相对于父项的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39967477/