html - 如何垂直 float /flex div然后水平继续

标签 html css flexbox css-float

我有一个由许多不同客户自定义的布局,因此 html 结构被锁定为

<div class="container">
    <div>content</div>
    <div>content</div>
    <div>content</div>
    <div>content</div>
</div>

注意:不使用 Bootstrap ,容器只是适用的名称

在 UI 中,我需要能够使用 CSS 根据该结构制作许多不同的布局,而无需更改它。特别是有一个我想不通。所需的布局是这样的:

enter image description here

我知道,如果它都是垂直的,那么使用简单的 widthfloat 样式就很容易实现。我也知道在前两个 child 周围放置一个包含 div 将是一个简单的解决方案,但再次要求保持 html 不变。

我试过:

.container {
    display: flex;
    flex-wrap: wrap;
}

.container > div {
    width: 33.33335;
    height: 400px;
}

.container > div:nth-child(1),
.container > div:nth-child(2) {
    height: 200px;
}

为子 div 设置适当的高度,其中前两个是其他高度的一半。

同样,我试过:

.container > div {
    float: left;
}

.container > div {
    height: 400px;
    width: 33.33333%;
}

.container > div:nth-child(1),
.container > div:nth-child(2) {
    height: 200px;
}

再次给前两个 child 一个高度,是其他 child 的一半。没有任何效果,在所有结果中,前两个堆栈和其他堆栈不 float /flex ,或者前两个根本不堆栈。

谁能想出一种 CSS 方法来为所需的 UI 设置此结构的样式?

感谢您的帮助。

最佳答案

如果可以在容器上设置固定高度,则可以使用带有 flex-flow: column wrap 的 flexbox。固定高度对于告诉 flex 元素在哪里包装是必要的。这是一个例子:

.container {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  justify-content: space-around; /* vertical alignment */
  align-content: center;         /* horizontal alignment */
  height: 320px;                 /* essential for this method to work */
  background-color: lightyellow;
  border: 1px dashed red;
}

.container>div {
  flex: 0 0 90%;                 /* flex-grow, flex-shrink, flex-basis */
  width: 30%;
  margin: 5px;
  background-color: lightgreen;
}

.container>div:nth-child(1),
.container>div:nth-child(2) {
  flex-basis: 40%;              /* override flex-basis from rule above */
}
<div class="container">
  <div>content</div>
  <div>content</div>
  <div>content</div>
  <div>content</div>
</div>

关于html - 如何垂直 float /flex div然后水平继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43058116/

相关文章:

html - 从部分 HTML 页面中删除样式

javascript - 使 div 顶部的两个 div 在滚动后固定并在再次滚动到顶部时重置?

html - 窗口最大化时,导航栏按钮不会正确对齐

html - 带有 overflow-y 的段落 :scroll is displacing my downside Div

html - 将字体保持在 float 左 div 中以保持在左边距

php - 使用 PHP 设置 LESS CSS 颜色

html - 如何仅使用CSS使父div的宽度等于子图像的宽度,子图像的高度等于父div的高度

javascript - 具有动态行数和列数的表格,垂直排序

html - 如何将元素对齐到中心?

css - 试图使 flex 元素等高但 flex-grow 不起作用