Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

html - How to start a new line with a particular item with Flexbox?

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 blocks in a row

I need the 5th block ("bloque 5") in red to be under the other four using Flexbox. The result should be:

4 blocks in a row and 1 in another row

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

  • for wrapping a flexbox, you need to give flex-wrap: wrap on the flexbox container,

  • to get 4 items per row, you can use flex-basis as 25% and adjust for the margin using calc,

  • to get the rows with less that 4 items fill the available space, you can consider flex-grow: 1 on the flex items too,

  • also consider adding box-sizing: border-box on the element* so that the padding is included in the width (and therefore in flex-basis)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...