James B
James B

Reputation: 9595

Prevent flex box item shrinking after wrap

For the HTML

<section class="flex-container">
<div class="item"></div>
<div class="item"></div>
</section>

I have defined the following css

.flex-container {
  display: flex;
  flex-wrap: wrap;
  min-height: 100vh;

  .item {
    background-color: #6f42c1;
    flex: 3;
  }

  .item:nth-child(2) {
    background-color: #0c5460;
    flex: 5;
  }

  @media (max-width: 768px) {
    .item:first-child {
      flex-basis: 100%;
    }
    .item:nth-child(2) {
      flex-shrink: 0;
    }
  }
}

When the viewport is greater than 768px I get the desired behaviour, i.e., two divs taking up a proportion of the screen, see below

enter image description here

but when I drop below 768px, my second item (green div) disappears

enter image description here

How can I adjust my css such that I maintain proportioned divs after the flex items have wrapped?

Upvotes: 0

Views: 83

Answers (1)

Temani Afif
Temani Afif

Reputation: 272842

Simply change the direction:

body {
 margin:0;
}

.flex-container {
  display: flex;
  flex-wrap: wrap;
  min-height: 100vh;
}

.item {
  background-color: #6f42c1;
  flex: 3;
}

.item:nth-child(2) {
  background-color: #0c5460;
  flex: 5;
}

@media (max-width: 768px) {
  .flex-container {
    flex-direction: column;
  }
}
<section class="flex-container">
  <div class="item"></div>
  <div class="item"></div>
</section>

Upvotes: 1

Related Questions