CptDayDreamer
CptDayDreamer

Reputation: 1794

Angular mat-form-field center alignment

Everywhere you can find how to center the text and even placeholder and labels and everything but I can't center the whole form-field and it looks ugly as hell.

<div class="mat-app-background basic-container">
  <div layout-gt-sm="column" style="min-width: 350px; max-width: 450px; margin:auto">
    <mat-card flex-gt-sm class="push">
      <div style="text-align:center;">
        <mat-card-title>Login</mat-card-title>
      </div>
      <div style="text-align:center;">
      <mat-card-content>
        <form [formGroup]="loginForm" class="form" (ngSubmit)="login()">
          <table cellspacing="0">
            <tr>
              <td>
                <mat-form-field>
                    <div style="text-align:center;">
                  <input matInput placeholder="{{ 'LOGIN.USERNAME' | translate }}" name="username"
                    formControlName="username" type="name" />
                  <mat-error *ngIf="formErrors.username" class="form__error">{{ formErrors.username }} </mat-error>
                </div>
                </mat-form-field>
              </td>
            </tr>

I hope this code needs. If not I will post the rest of the html. But it's just about centering the fields. Didn't used CSS here.

Upvotes: 9

Views: 59894

Answers (2)

Fabricio Leite
Fabricio Leite

Reputation: 338

You can put style="text-align:center;" inside input element.

<mat-form-field appearance="outline" [style.width.em]="8">
    <mat-label>Início</mat-label>
    <input style="text-align:center;" type="text" maxlength="10" matInput formControlName="segundaInicio">
</mat-form-field>

Upvotes: 1

wentjun
wentjun

Reputation: 42596

I would recommend you to use flexbox.

I am also not sure why do you need to put it inside a , but I have removed it to simplify the demo.

<div class="parent">
  <mat-form-field>
    <div style="text-align:center;">
      <input matInput placeholder="{{ 'LOGIN.USERNAME' | translate }}" name="username" formControlName="username" type="name" />
      <mat-error *ngIf="formErrors.username" class="form__error">{{ formErrors.username }} </mat-error>
    </div>
  </mat-form-field>
</div>

And on your CSS,

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

The properties justify-content and align-items with the value of center will center the flex children along the line and in the cross-axis respectively, thus placing them on the centre of the page. The property flex-direction with the value of column aligns the children (form fields) from top to bottom.

Upvotes: 19

Related Questions