[英]Wrap element to new line/row using flexbox
I have trouble forcing an item into the next row in a flexbox layout. 我无法强迫项目进入flexbox布局的下一行。
How can I do something like the following image? 我该如何做以下图片?
This is what I got so far: 这是我到目前为止所得到的:
#wrap { display: flex; width: 86vw; height: auto; box-sizing: border-box; margin: 0 auto; } .item1, .item2 { width: 50%; height: 24.5vw; background: #4add69; } .item1 { margin-right: 10px; } .item2 { margin-left: 10px; } .item3 { width: 60%; height: 40vw; background: #d56c6c; }
<div id="wrap"> <div class="item1"></div> <div class="item2"></div> <div class="item3"></div> </div>
Your code is fine but missing two things. 你的代码很好,但缺少两件事。
Use flex-wrap: wrap
to create a new row. 使用flex-wrap: wrap
来创建一个新行。 Modify the width of the first two items to be present in a single row. 修改单个行中存在的前两个项的宽度。
For the last two items, you need to nest it inside a container and then wrap them again. 对于最后两项,您需要将其嵌套在容器中,然后再次包装它们。
Manipulate the dimension(width, height) and margin values to achieve the perfect/suitable layout. 操纵尺寸(宽度,高度)和边距值以实现完美/合适的布局。
* { margin: 0; padding: 0; } body { background: #232323; padding: 10px; } #wrap { display: flex; width: 86vw; height: auto; box-sizing: border-box; margin: 0 auto; flex-wrap: wrap; background: #232323; /* Added */ } .item1, .item2 { width: 48%; /* Modified */ height: 24.5vw; background: #4add69; margin-bottom: 10px; } .item1 { margin-right: 10px; } .item2 { margin-left: 10px; } .item3 { width: 55%; height: 40vw; background: #d56c6c; margin-right: 10px; } .nested-items { display: flex; width: 42%; flex-wrap: wrap; align-content: space-between; } .item4, .item5 { background: lightblue; width: 100%; height: 49%; }
<div id="wrap"> <div class="item1"></div> <div class="item2"></div> <div class="item3"></div> <div class="nested-items"> <div class="item4"></div> <div class="item5"></div> </div> </div>
Essentially you need an extra wrapping div for the two 'small' elements like so: 基本上你需要一个额外的包装div为两个'小'元素,如下所示:
* { margin: 0; padding: 0; box-sizing: border-box; } .wrap { width: 75%; margin: 1em auto; border: 1px solid green; padding: .25em; display: flex; flex-wrap: wrap; } .wrap div { border: 1px solid grey; margin-bottom: 1px; } .box { height: 80px; background: lightblue; flex: 0 0 50%; } .tall { flex: 0 0 65%; height: 160px; } .col { flex: 0 0 35%; display: flex; flex-wrap: wrap; } .mini { flex: 0 0 100%; height: 80px; background: pink; }
<div class="wrap"> <div class="box"></div> <div class="box"></div> <div class="box tall"></div> <div class="box col"> <div class="mini"></div> <div class="mini"></div> </div> </div>
I've used a single overall element here with wrapping but the image suggests that this would be much simpler with actual rows and the extra wrapper mentioned before. 我在这里使用了一个带有包装的单个整体元素,但是图像表明这对于实际的行和之前提到的额外包装来说会更简单。
Codepen Demo of 2nd option with rows. Codepen演示第二个选项与行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.