Home > other >  Flexbox - How to split row 50/50 between two elements and wrap if width falls below min-width?
Flexbox - How to split row 50/50 between two elements and wrap if width falls below min-width?

Time:03-21

I have a simple div which contains two mat-cards. Here are the CSS attributes of the div and of the cards inside the div:

.cards {
  display: flex;
  flex-wrap: wrap;
  align-content: center;
  justify-content: center;
}

mat-card {
  margin: 10px;
  width: 45%;
  min-width: 300px;
}

Here is an example HTML template to reproduce the problem:

<div >
  <mat-card>
    <mat-card-header>
      <mat-card-title> Card 1 </mat-card-title>
    </mat-card-header>
    <mat-card-content>
      Name: Test 1 <br />
      Type: Type 1 <br />
      Property 1: 1 <br />
      Property 2: 2 <br />
      Property 3: 3 <br />
    </mat-card-content>
  </mat-card>
  <mat-card>
    <mat-card-header>
      <mat-card-title> Card 2 </mat-card-title>
    </mat-card-header>
    <mat-card-content>
      Name: Test 2 <br />
      Type: Type 2 <br />
      Property 1: 1 <br />
      Property 2: 2 <br />
      Property 3: 3 <br />
    </mat-card-content>
  </mat-card>
</div>

I want each of the cards to fill 50% of the row. If the min-width of the cards is too large to fit both cards into the row, the div content should wrap so the cards are now below each other. After the wrap, each card should fill 100% of the available width.

With my current CSS layout, the content wraps way too early and I also can't seem to just set the width of the cards to 50% each because this causes it to wrap immediately. Here is a stackblitz which illustrates the problem: StackBlitz

How can I get the desired behavior?

CodePudding user response:

Just change width: 45% to flex-grow: 1, the flex items will try to take up the whole row. flex-basis controls how large they are in relation to eachother, by default they will attempt to stay the same size. Currently they wrap at 332px because of the 16px of padding.

mat-card {
  margin: 10px;
  min-width: 300px;
  flex-grow: 1;
}
  • Related