Dr.Li
Dr.Li

Reputation: 45

Break 4 divs in 2 row and 2 columns responsive

could you pleae help me. I have 4 Divs in one row.

<div class="container">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
</div>

Now I want to move 2 of them to the next row if the width is <768px.

I have achieved this with the CSS grid

.container {
    display: grid;
    rid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    grid-template-rows: repeat(4, minmax(300px, auto));
    justify-content: center;
}

  @media only screen and (min-device-width: 768px) and (max-device-width: 1024px) {
    .container {
         grid-template-columns: 40% 40%;
    }
 }

But unfortunately CSS Grid is not well supported in the IE Browser Version < Edge. So I have tried with display:flex, but cannot achieve the same result.

Here example

enter image description here

Can anybody help me out?

Solution was found:

.container{
    display: flex;
    flex-wrap: wrap;
}


.item {
    flex: 25%;
    max-width: 25%;
}


@media (max-width: 800px) {
    .item {
        flex: 50%;
        max-width: 50%;
    }
}


@media (max-width: 600px) {
    .item {
        flex: 100%;
        max-width: 100%;
    }
}

Upvotes: 1

Views: 5577

Answers (2)

לבני מלכה
לבני מלכה

Reputation: 16251

Use flex and order:1

See fiddle:https://jsfiddle.net/tmg08h34/

  .container{
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
    }
.container:after {
  content: '';
  width: 100%;
}
    @media only screen and (min-width: 768px) and (max-width: 1024px) {
        .container .item:nth-child(n + 3){
            order: 1;
        }
     }
 <div class="container">
        <div class="item">1</div>
        <div class="item">2</div>
        <div class="item">3</div>
        <div class="item">4</div>
    </div>

Edit to your comment work in IE

.container{
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
}
 @media only screen and (min-width: 768px) and (max-width: 1024px) {
.container .item:nth-child(2n) {
padding-right: 100%;
 }

}
 <div class="container">
        <div class="item">1</div>
        <div class="item">2</div>
        <div class="item">3</div>
        <div class="item">4</div>
    </div>

Upvotes: 1

Yashwardhan Pauranik
Yashwardhan Pauranik

Reputation: 5566

Set your .container class to display:flex and flex-wrap: wrap.

So when the device screen width will be small to accommodate the .item boxes, they will be wrapped to another row.

.container {
  display: flex;
  flex-wrap: wrap;
}

.item {
  width: 80px;
  height: 80px;
  border: 1px solid #eee;
}

Upvotes: 1

Related Questions