我有以下代码:
* {
box-sizing: border-box;
}
.blue {
color: #fff;
background-color: blue;
flex: 0 0 50%;
max-width: 50%;
padding: 0 15px;
}
.violet {
color: #fff;
background-color: blueviolet;
flex: 0 0 50%;
max-width: 50%;
padding: 0 15px;
}
.div {
background: black;
color: white;
margin: 50px auto;
display: flex;
margin-left: -15px;
margin-right: -15px;
}
.xont {
width: 60%;
margin: auto;
padding-left: 15px;
padding-right: 15px;
}
<div class="xont">
<div class="div">
<div class="violet">This is div 1</div>
<div class="blue">This is div 2</div>
</div>
</div>
为什么 .div
元素的宽度增加了 30px 当我将左右的负边距设置为 -15px 时?
最佳答案
这里是规范中描述如何计算 block 元素宽度的部分:https://www.w3.org/TR/CSS21/visudet.html#blockwidth .
公式为:
The following constraints must hold among the used values of the other properties:
'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block
您还可以阅读:
If 'width' is set to 'auto', any other 'auto' values become '0' and 'width' follows from the resulting equality.
所以填充和边框我们是 0,我们将有:
'margin-left' + 'width' + 'margin-right' = 包含 block 的宽度
然后
'width' = 包含 block 的宽度 - 'margin-left' - 'margin-right'
现在很清楚,如果边距为负,则元素的宽度将增加到超过包含 block 的宽度。
关于html - 为什么 CSS 左右边距会增加元素的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55664770/