在两个元素之间拆分 space 时的额外像素

Extra pixels when splitting space between two elements

我有一个包含两个 children 的块元素,我希望它们每个占据 space 的一半,减去它们之间的 fixed-size 间隙。使用 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 parent 和 children 应该是 50% - 5px = 145px 宽,加上 5px 边距。这意味着两个 children 加上它们的边距应该恰好占据 300px。当我这样设置时,它们会换行。如果我每 child 减去额外的 2 个像素,它们似乎会准确地填充 space,即使它们每个仅测量 148 像素(包括边距)。额外的像素来自哪里?

是左右div之间的白色space

如果你去掉它们之间的白色 space 就可以了,即:

<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();
#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>

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;
}
<div id="container">
  <div id="left"></div>
  <div id="right"></div>
</div>

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;
}
<div id="container">
  <div id="left"></div>
  <div id="right"></div>
</div>