我有一个带有两个孩子的块元素,我希望它们每个占据一半的空间,减去它们之间固定大小的间隙。这应该很容易calc()
:
var left = document.getElementById("left");
var right = document.getElementById("right");
var info = document.getElementById("info");
var offset = 5;
function toggleStyle() {
if (offset === 5) {
offset = 7;
} else {
offset = 5;
}
info.innerHTML = right.style = left.style = "width: calc(50% - " + offset + "px);";
}
toggleStyle();
#container {
width: 300px;
height: 160px;
background-color: green;
}
#left, #right {
display: inline-block;
background-color: blue;
height: 150px;
margin-top: 5px;
margin-bottom: 5px;
}
#left {
margin-right: 5px;
}
#right {
margin-left: 5px;
}
<div id="info"></div>
<button onclick="toggleStyle()">Toggle</button>
<div id="container">
<div id="left"></div>
<div id="right"></div>
</div>
在上面的代码段中,我有一个 300px 的父级,其子级应该是50% - 5px
= 145px 宽,加上每个 5px 的边距。这意味着两个孩子,加上他们的边距,应该正好占据 300px。当我以这种方式设置时,它们会包装。如果我为每个孩子减去额外的 2 个像素,它们似乎完全填充了空间,即使它们每个仅测量 148 像素(包括边距)。额外的像素从何而来?