How to replace following flex layout code with CSS Flexbox code?

4.3k views Asked by At

Since @angular/flex-layout is deprecated, I want to move from that library towards CSS Flexbox. I want to convert following code to the equivallent CSS Flexbox code. And get rid of that library.

 <div fxLayout="row wrap" fxLayoutGap="16px grid" fxLayoutAlign="space-evenly none">

  <div *ngFor="let product of products" fxFlex.xs="calc(90% - 16px)" fxFlex.sm="0 0 calc(50% - 16px)"
    fxFlex="0 0 calc(33% - 16px)">

    <app-product-list-card [product]="product"></app-product-list-card>

  </div>

</div>

What about writing a common class at global styles.scss and using it in multiple places in angular application?

2

There are 2 answers

0
Mr. Stash On

It isn't easy to achieve the effects of directives in CSS but you can try something like this

<div
  class="
    fx fx-row-wrap fx-layout-align-stretch fx-layout-align-space-evenly-stretch
  "
>
  <div *ngFor="let product of products" class="product">
    <app-product-list-card [product]="product"></app-product-list-card>
  </div>
</div>
.fx {
  display: flex;
}

.fx-row-wrap {
  flex-flow: row wrap;
}

.fx-layout-align-space-evenly-stretch {
  place-content: stretch space-evenly;
  align-items: stretch;
}

.product {
  flex: 0 0 calc(33% - 16px);
  box-sizing: border-box;
  max-width: calc(33% - 16px);
  min-width: calc(33% - 16px);

  @media screen and (max-width: 599px) {
    flex: 1 1 calc(90% - 16px);
    box-sizing: border-box;
    min-width: calc(90% - 16px);
    max-width: 100%;
  }

  @media screen and (min-width: 600px) and (max-width: 959px) {
    flex: 0 0 calc(50% - 16px);
    box-sizing: border-box;
    min-width: calc(50% - 16px);
    max-width: calc(50% - 16px);
  }
}
0
philmtd On

It will not cover all your selectors in the example but this library can replace most of the popular Flex-Layout selectors: https://github.com/philmtd/css-fx-layout