我有一个有两个孩子的块元素,我喜欢它们各占一半的空间,减去它们之间的固定大小的间隙。 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>
&#13;
在上面的代码片段中,我有一个300px的父级,其子级应为50% - 5px
= 145px宽,每个加5px边距。这意味着这两个孩子加上他们的边缘应该占据300px。当我这样设置时,它们会换行。如果我为每个孩子减去额外的2个像素,它们似乎准确地填充空间,即使它们每个仅测量148px(包括边距)。额外像素来自哪里?
答案 0 :(得分:2)
它是左右div之间的空白区域。
如果你删除它们之间的空格,它将起作用,即:
<div id="container">
<div id="left"></div><div id="right"></div>
</div>
工作片段:
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();
&#13;
#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;
}
&#13;
<div id="info"></div>
<button onclick="toggleStyle()">Toggle</button>
<div id="container">
<div id="left"></div><div id="right"></div>
</div>
&#13;
答案 1 :(得分:1)
Flexbox 可以做到这一点
#container {
width: 300px;
margin: 1em auto;
height: 160px;
background-color: green;
display: flex;
}
#left,
#right {
background-color: lightblue;
height: 150px;
margin-top: 5px;
margin-bottom: 5px;
flex: 1;
}
#left {
margin-right: 5px;
}
&#13;
<div id="container">
<div id="left"></div>
<div id="right"></div>
</div>
&#13;
CSS Grid 也可以这样做。
#container {
width: 300px;
margin: 1em auto;
height: 160px;
background-color: green;
display: grid;
grid-template-columns: 1fr 1fr;
grid-gap: 5px;
}
#left,
#right {
background-color: lightblue;
height: 150px;
margin-top: 5px;
margin-bottom: 5px;
}
&#13;
<div id="container">
<div id="left"></div>
<div id="right"></div>
</div>
&#13;