首页 > 解决方案 > 一旦单个元素包裹,其余元素也会包裹

问题描述

我有一个页面,其中包含一段内联块,我想要完成的是让它们都在同一行,如果它们适合的话,但是一旦其中一个包裹我希望它们全部包裹到新的线。我对一些连续的 javascript 位置/宽度检查有一个想法,但我希望在 CSS 或引导程序中内置一些更干净的东西。

编辑:澄清一点-
每个块的宽度都是可变的,并且在页面加载后不会改变。
容器的宽度是可变的,并且可能会在页面加载后发生变化(调整浏览器窗口的大小/移动设备方向更改)。

这是一个示例小提琴,其中第一个容器是正确的预期行为,但底部容器我希望一切都包装: https ://jsfiddle.net/bxye0L4L/1/

<div class="wide-container">
  <div class="block one"></div>
  <div class="block two"></div>
  <div class="block three"></div>
</div>
<br>
<div class="narrow-container">
  <div class="block one"></div>
  <div class="block two"></div>
  <div class="block three"></div>
</div>

css

.wide-container {
  width: 700px;
  border: black solid;
}
.narrow-container {
  width: 500px;
  border: black solid;
}

.block {
  display: inline-block;
  width: 200px;
  height: 100px;
}
.one {
  background: red;
}
.two {
  background: green;
}
.three {
  background: blue;
}

标签: javascripthtmlcss

解决方案


在我看来,有 2 个简单的 css 选项。

a) 使“窄容器”更窄 - 从 500px 减少到例如 350 或 300

或者

b)您可以为底部容器创建一个单独的 css 类,如果您希望它们在另一个下方排列,则将它们设置为阻止。

狭窄的有500的理由吗?如果是这样,我会选择第二个选项。我包括片段

.wide-container {
  width: 700px;
  border: black solid;
}

.narrow-container {
  width: 500px;
  border: black solid;
}

.block {
  display: inline-block;
  width: 200px;
  height: 100px;
}

.iblock {
  display: block;
  width: 200px;
  height: 100px;
  margin: 3px 0px;
}

.one {
  background: red;
}

.two {
  background: green;
}

.three {
  background: blue;
}
<div class="wide-container">
  <div class="block one"></div>
  <div class="block two"></div>
  <div class="block three"></div>
</div>
<br>
<div class="narrow-container">
  <div class="iblock one"></div>
  <div class="iblock two"></div>
  <div class="iblock three"></div>
</div>

.wide-container {
  width: 700px;
  border: black solid;
}
.narrow-container {
  width: 300px;
  border: black solid;
}

.block {
  display: inline-block;
  width: 200px;
  height: 100px;
}
.one {
  background: red;
}
.two {
  background: green;
}
.three {
  background: blue;
}
<div class="wide-container">
  <div class="block one"></div>
  <div class="block two"></div>
  <div class="block three"></div>
</div>
<br>
<div class="narrow-container">
  <div class="block one"></div>
  <div class="block two"></div>
  <div class="block three"></div>
</div>


推荐阅读