Search code examples
htmlcsslayoutflexbox

HTML5, CSS3 flex box not working properly


I've learned that display flex help me reduce working hours for publishing. However I've got a problem that the layout didn't display what I want.

All I want to display like grid layout like below :

enter image description here

But unfortunately I cannot fix this issue by myself. Could you give me an advice how can I fix this issue with flex tag?

You can see my problem like below too :

enter image description here

Here is my code :

.item_wrap {
   display: flex; 
   justify-content: space-between;
   flex-flow: row-wrap;
}

.item_0 {
   width: 500px; 
   height: 500px; 
   background: #ff0;
}

.item_1 {
   width: 490px; 
   height: 160px; 
   background: #00f;
}

.item_2 {
   width: 240px; 
   height: 160px; 
   background: #ff00e4;
}

.item_3 {
   width: 240px; 
   height: 160px; 
   background: #ff00e4;
}

.item_4 {
   width: 240px; 
   height: 160px; 
   background: #1cc600;
}

.item_5 {
   width: 240px; 
   height: 160px; 
   background: #1cc600;
}

Solution

  • You will need to change HTML structure.

    All blocks on the right side should be wrapped in a <div>.

    HTML:

    <div class="item-wrap">
      <div class="item_0">0</div>
      <div class="inner-wrap">
        <div class="item_1">1</div>
        <div class="item_2">2</div>
        <div class="item_3">3</div>
        <div class="item_4">4</div>
        <div class="item_5">5</div>
      </div>
    </div>
    

    CSS:

    .item-wrap {
      justify-content: space-between;
      display: flex;
    }
    .inner-wrap {
      justify-content: space-between;
      flex-wrap: wrap;
      display: flex;
    }
    .item_0,
    .inner-wrap {
      flex-basis: calc(50% - 5px);
    }
    .inner-wrap > div {
      flex-basis: calc(50% - 5px);
    }
    .inner-wrap > .item_1 {
      flex-basis: 100%;
    }
    

    * {box-sizing: border-box;}
    body {
      margin: 0;
    }
    .item-wrap {
      justify-content: space-between;
      height: 100vh;
      display: flex;
    }
    .inner-wrap {
      justify-content: space-between;
      flex-wrap: wrap;
      display: flex;
    }
    .item_0,
    .inner-wrap {
      flex-basis: calc(50% - 5px);
    }
    .inner-wrap > div {
      flex-basis: calc(50% - 5px);
      padding: 10px;
    }
    .inner-wrap > div + div {
      margin-top: 10px;
    }
    .inner-wrap > .item_1 {
      flex-basis: 100%;
    }
    .item_0{background:#ff0; padding: 10px;}
    .item_1{background:#00f;}
    .item_2{background:#ff00e4;}
    .item_3{background:#ff00e4;}
    .item_4{background:#1cc600;}
    .item_5{background:#1cc600;}
    <div class="item-wrap">
      <div class="item_0">0</div>
      <div class="inner-wrap">
        <div class="item_1">1</div>
        <div class="item_2">2</div>
        <div class="item_3">3</div>
        <div class="item_4">4</div>
        <div class="item_5">5</div>
      </div>
    </div>