如何使用Flexbox从特定项目开始新行? [英] How to start a new line with a particular item with Flexbox?
问题描述
这是一个非常简单的练习,但我似乎找不到一种整齐的方法来解决它(刚刚开始学习HTML和CSS)。
This is a very simple exercise but I can't seem to find a neat way to solve it (just started learning about HTML and CSS).
我需要第5个块(使用Flexbox将红色的空白5)显示在其他四个下方。
结果应为:
I need the 5th block ("bloque 5") in red to be under the other four using Flexbox. The result should be:
有人可以帮我吗?到目前为止,这是我所拥有的:
Could somebody help me with this, please? This is what I have so far:
div {
margin: 5px;
border: 1px solid pink;
padding: 5px;
font-family: arial, sans-serif;
font-size: 14px;
}
.contenidor {
width: 760px;
display: flex;
}
div[class*=element] {
width: 100%;
padding: 2px 30px 5px 2px;
}
.element5 {
background-color: red;
}
<div class="contenidor">
<div class="element1">bloque 1</div>
<div class="element2">bloque 2</div>
<div class="element3">bloque 3</div>
<div class="element4">bloque 4</div>
<div class="element5">bloque 5</div>
</div>
推荐答案
在flexbox中连续包含 n个项目的要点是 padding 和 margin 也必须考虑,因为您正在包装弹性盒。我在您的代码中做了以下更改:
The gist of having n items in a row with flexbox is that padding and margin must also be considered because you are wrapping the flexbox. I made the following changes in your code:
-
为包装flexbox,您需要给
flex -wrap:在 flexbox容器上包装
for wrapping a flexbox, you need to give
flex-wrap: wrap
on the flexbox container,
每行获取4个项目,您可以使用 flex-basis
作为25%,并使用 calc
,
to get 4 items per row, you can use flex-basis
as 25% and adjust for the margin using calc
,
要获得少于4个项目的行填充可用空间,您可以考虑 flex-grow:1
在 flex项目上,
to get the rows with less that 4 items fill the available space, you can consider flex-grow: 1
on the flex items too,
也考虑添加 box-sizing:border-box
上的code> * ,以便将 padding 包含在 width 中(因此, flex-basis
)
also consider adding box-sizing: border-box
on the element*
so that the padding is included in the width (and therefore in flex-basis
)
您可以在此处找到类似的问题: 连续排列5个项目
。参见下面的演示:
You can find a similar question here: arranging 5 items in a row
. See demo below:
div {
margin: 5px;
border: 1px solid pink;
padding: 5px;
font-family: arial, sans-serif;
font-size: 14px;
}
.contenidor {
width: 760px;
display: flex;
flex-wrap: wrap; /* wrapping flexbox */
}
div[class*=element] {
/*width: 100%;*/
padding: 2px 30px 5px 2px;
box-sizing: border-box; /* adjusts for padding */
flex-grow: 1; /* expand to fill remaining space */
flex-basis: calc(25% - 10px); /* 4 items per row, adjust for the 5px margin */
}
.element5 {
background-color: red;
}
<div class="contenidor">
<div class="element1">bloque 1</div>
<div class="element2">bloque 2</div>
<div class="element3">bloque 3</div>
<div class="element4">bloque 4</div>
<div class="element5">bloque 5</div>
</div>
这篇关于如何使用Flexbox从特定项目开始新行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!