Search code examples
angular-materialangular-flex-layoutangular-material-stepper

How to center horizontally material stepper by flex-layout?


I try to use in my project only flex-layout and avoid vanilla css. I cannot figure out how to center hohorizontally angular material stepper and get good view. I check margin: 0 auto; and it works properly. Here is my code:

<mat-vertical-stepper [linear]="true" #stepper fxLayoutAlign="center center" fxLayout="column">
  <mat-step>
    <form>
      <ng-template matStepLabel>
        Fill out ballot name
      </ng-template>
      <mat-form-field>
        <input matInput placeholder="Ballot name">
      </mat-form-field>
      <div>
        <button mat-flat-button matStepperNext>Next</button>
      </div>
    </form>
  </mat-step>

  <mat-step>
    <form fxLayout="column">
      <ng-template matStepLabel>
        Select start and end time
      </ng-template>
      <mat-form-field>
        <input matInput [matDatepicker]="pickerStart" placeholder="Choose a start date">
        <mat-datepicker-toggle matSuffix [for]="pickerStart"></mat-datepicker-toggle>
        <mat-datepicker #pickerStart></mat-datepicker>
      </mat-form-field>
      <mat-form-field>
        <input matInput [matDatepicker]="pickerEnd" placeholder="Choose a end date">
        <mat-datepicker-toggle matSuffix [for]="pickerEnd"></mat-datepicker-toggle>
        <mat-datepicker #pickerEnd></mat-datepicker>
      </mat-form-field>
      <div fxLayoutGap="5px">
        <button mat-flat-button matStepperPrevious>Back</button>
        <button mat-flat-button matStepperNext>Next</button>
      </div>
    </form>
  </mat-step>

  <mat-step>
    <form>
      <ng-template matStepLabel>
        Enter a description of ballot
      </ng-template>
      <mat-form-field>
        <textarea matInput placeholder="Description"></textarea>
      </mat-form-field>
      <div fxLayoutGap="5px">
        <button mat-flat-button matStepperPrevious>Back</button>
        <button mat-flat-button (click)="stepper.reset()">Reset</button>
        <button mat-flat-button>Confirm</button>
      </div>
    </form>
  </mat-step>
</mat-vertical-stepper>

Screenshot of the problem:

enter image description here


Solution

  • Each step is a different width, so the result you see is expected. When you horizontally center vertically stacked elements, wider elements will appear outside narrower elements. What you want is to center the whole stepper, and leave the steps left aligned:

    <div fxLayoutAlign="center center" fxLayout="column">
    
      <mat-vertical-stepper [linear]="true" #stepper>
        ...
      </mat-vertical-stepper>
    
    </div>
    

    StackBlitz