C. Banzet
C. Banzet

Reputation: 419

Same size of the last items with Flex Layout in the grid system

I have a problem using the flex layout grid system.

Let's say I have a grid of 6 items and I want 4 items per rows. So I would do like this :

<div fxFlex="100" fxLayout="row wrap" fxLayoutGap="1px">
<div fxFlex="calc(25% - 1px)" fxLayoutAlign="center end" *ngFor="let item of items">
    <span fxFlex>{{ item }}</span>
</div>
</div>

The problem with this code is that the last two items on the second row have a different size than the items on the first row. They would have a size of 50% of the full size row but the item of the first row would be 25% of the full size row.

So how would I do to have all items with 25% of the full size row on two rows?

Upvotes: 0

Views: 4255

Answers (2)

Narm
Narm

Reputation: 10864

The issue with your code is a combination of the fxLayoutGap="1px" in the parent flex container as well as the fxFlex="calc(25% - 1px)" in your flex children.

If you simply remove the fxLayoutGap="1px" and change your children to fxFlex="25" you will get the desired behavior. However, that will result in your gap being removed.

If you really want to keep you gap than I suggest you be consistent and use a percent like the following example: Here is the working stackBlitz

<div fxFlex="100" fxLayout="row wrap" fxLayoutGap=".2%">
      <div fxFlex="24" fxLayoutAlign="center end">
        <span style="background-color: green" fxFlex>1</span>
      </div>
      <div fxFlex="24" fxLayoutAlign="center end">
        <span style="background-color: yellow" fxFlex>2</span>
      </div>
      <div fxFlex="24" fxLayoutAlign="center end">
        <span style="background-color: blue" fxFlex>3</span>
      </div>
      <div fxFlex="24" fxLayoutAlign="center end">
        <span style="background-color: orange" fxFlex>4</span>
      </div>
      <div fxFlex="24" fxLayoutAlign="center end">
        <span style="background-color: pink" fxFlex>5</span>
      </div>
      <div fxFlex="24" fxLayoutAlign="center end">
        <span style="background-color: red" fxFlex>6</span>
      </div>
    </div>

Upvotes: 0

Tommy
Tommy

Reputation: 2453

The answer is using fxFlex="25" instead of fxFlex="calc(25% - 1px)" and removing fxLayoutGap and solve this by adding padding: 1px for example.

I have create a stackblitz to show this possible solution (width padding: 3px):

<div fxFlex="100" fxLayout="row wrap">
    <div fxFlex="25" fxLayoutAlign="center end" *ngFor="let item of items" style="padding: 3px;">
        <span fxFlex>{{ item }}</span>
    </div>
</div>

If you do not want to remove fxLayoutGap use fxFlex="24" instead.

<div fxFlex="100" fxLayout="row wrap" fxLayoutGap="1px">
    <div fxFlex="24" fxLayoutAlign="center end" *ngFor="let item of items">
        <span fxFlex>{{ item }}</span>
    </div>
</div>

Upvotes: 4

Related Questions