gpt4 book ai didi

css - 当有足够的空间时,Flexbox 将一个 div 放置在其他 div 的右侧

转载 作者:行者123 更新时间:2023-11-28 16:20:15 25 4
gpt4 key购买 nike

假设我们有四个 div。在小屏幕上,我希望它们看起来像下图。 4 个盒子一个叠一个,很好地居中。很容易。 4 boxes stacked one on top of the other

一旦屏幕足够大,我希望行中的第 3 个 div 弹出到右侧,同时仍然保持其他 3 个堆叠在左侧。我如何使用 flexbox 或其他一些 css 技术做到这一点?

非常感谢。我确定这是重复的,但我无法找到我的确切场景。 four boxes with the 3rd one to the right of the others

最佳答案

如果您使用 @media查询断点,您可以使用 flex-wrap: wrap 重新排序 flex 子项并强制换行, 百分比宽度和 margin-right对于 child2child4使它们的宽度与 child1 相同

body {
background: lightblue;
}

.flex {
display: flex;
flex-direction: column;
padding: 1em;
border:1px solid #000;
}

.flex .child {
font-size: 3em;
padding: 0.1em;
border: 1px solid #000;
margin-bottom: .5em;
box-sizing: border-box;
}

@media (min-width: 600px) {
.flex {
flex-direction: row;
flex-wrap: wrap;
}
.flex .child {
order: 3;
width: 33.33%;
}
.flex .child:nth-of-type(1) {
order: 1;
width: 33.33%;
}
.flex .child:nth-of-type(3) {
order: 2;
width: 66.66%;
}
.flex .child:nth-of-type(2), .flex .child:nth-of-type(4) {
margin-right: 66.66%;
}
}
<div class="flex">
<div class="child">1</div>
<div class="child">2</div>
<div class="child">3</div>
<div class="child">4</div>
</div>

jsFiddle: https://jsfiddle.net/azizn/3snvjyp5/


编辑:动态高度/仿砌体布局

如果你想要child3要在不创建空白的情况下拥有较高的高度,您可以申请 position: absolute这样它就不会影响流程,而所有其他 child 都在 margin-right 之下。等于 child3的宽度:

body {
background: lightblue;
}

.flex {
display: flex;
flex-direction: column;
padding: 1em;
border:1px solid #000;
position: relative;
}

.flex .child {
font-size: 3em;
padding: 0.1em;
border: 1px solid #000;
margin-bottom: .5em;
box-sizing: border-box;
}

@media (min-width: 600px) {
.flex {
flex-direction: row;
flex-wrap: wrap;
}
.flex .child {
width: 33.33%;
margin-right: 66.66%;
}
.flex .child:nth-of-type(3) {
width: 62.66%;
position: absolute;
top: 2%; right: 2%;
margin-right: 0;
}
}
<div class="flex">
<div class="child" style="height: 100px;">1</div>
<div class="child" style="height: 200px;">2</div>
<div class="child" style="height: 600px;">3</div>
<div class="child" style="height: 400px;">4</div>
</div>

此代码更加简化,因为我们不需要对子项重新排序。

jsFiddle:https://jsfiddle.net/azizn/d0pk8p89/

关于css - 当有足够的空间时,Flexbox 将一个 div 放置在其他 div 的右侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36976641/

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