Search code examples
htmlcssflexboxalignment

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>


Solution

  • 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>