gpt4 book ai didi

html - 在同一容器中对齐具有不同高度的 flex 元素

转载 作者:太空狗 更新时间:2023-10-29 14:43:47 25 4
gpt4 key购买 nike

我想知道是否有可能让 flex 元素与同一容器中较大的 flex 元素水平对齐。使用 CSS float 很容易完成,但我无法使用 flex 元素完成它。

View this JSFiddle for a flexbox example.

View this JSFiddle a float example

网格布局

<div class="flex-container">
<div class="large-flex-item">
</div>
<div class="small-flex-item">
</div>
<div class="small-flex-item">
</div>
</div>

CSS

 .flex-container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
align-items: flex-start;
max-width: 500px;
margin-right: auto;
margin-left: auto;
}

.small-flex-item {
flex-basis: 33.333%;
background: #000;
padding-top: 30%;
}

.large-flex-item {
flex-basis: 66.667%;
background: #333;
padding-top: 60%;
}

最佳答案

Flexbox 不喜欢通过多列或多行扩展的 flex 元素,因为实际上 flexbox 没有网格概念。

但是,使用一些技巧,您可以实现此布局(以及 more complicated ones):

  • 使用行布局

    ┌─┬─┬─┐
    │1│2│3│
    └─┴─┴─┘
  • 允许使用 flex-wrap: wrap 换行。

  • 使用伪元素强制在 2 之后换行

    ┌─┬─┐
    │1│2│
    ├─┼─┘
    │3│
    └─┘
  • 在 2 和 3 上使用 width: 33%,在 1 上使用 flex: 1

    ┌───────────────┬─────┐
    │1 │2 │
    ├─────┬─────────┴─────┘
    │3 │
    └─────┘
  • margin-left: auto 设置为 3

    ┌───────────────┬─────┐
    │1 │2 │
    └───────────────┼─────┤
    │3 │
    └─────┘
  • 选择一些长度x

  • height: x 设置为 2 和 3。将 height: 2*x 设置为 1。

    ┌───────────────┬─────┐
    │1 │2 │
    │ ├─────┘
    │ │
    └───────────────┼─────┐
    │3 │
    └─────┘
  • margin-bottom: -x 设置为 1:

    ┌───────────────┬─────┐
    │1 │2 │
    │ ├─────┤
    │ │3 │
    └───────────────┴─────┘
  • 注意 flexbox 引入 auto 作为 min-width 的新初始值。这可能会让内容迫使一些盒子变大。这会破坏布局,因此请使用 min-width: 0 禁用它或将 overflow 设置为 visible 以外的任何值。

    <

代码如下:

.flex-container {
display: flex;
flex-flow: row wrap;
}
.flex-item {
overflow: hidden;
}
.flex-container::after {
content: '';
width: 100%; /* Force line break */
}
.large.flex-item {
flex: 1;
height: 200px;
margin-bottom: -100px;
background: red;
}
.small.flex-item {
width: 33.333%;
height: 100px;
background: green;
}
.small.flex-item + .small.flex-item {
order: 1;
margin-left: auto;
background: blue;
}
<div class="flex-container">
<div class="large flex-item">1</div>
<div class="small flex-item">2</div>
<div class="small flex-item">3</div>
</div>

但是,修改 HTML 以获得嵌套的 flexbox 会更容易。

关于html - 在同一容器中对齐具有不同高度的 flex 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34069504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com