1

我有一个带有两个孩子的块元素,我希望它们每个占据一半的空间,减去它们之间固定大小的间隙。这应该很容易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 像素(包括边距)。额外的像素从何而来?

4

2 回答 2

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

于 2017-09-27T09:15:55.197 回答
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;
}
<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>

于 2017-09-27T09:38:41.060 回答