Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with CSS for mat-input and mat-form-field

I tried doing a stackblitz but it doesn't accept my <mat-form-field> and <mat-label> tags without errors, I imported the needed components but it won't work.

But maybe you can help me anyway if I post here the code, I'm having an issue with CSS as I don't know what to target to move the <mat-label> tag, when I use a <mat-form-field> with appearance="outline" when the label is in the center, over the input field, I can't move it, I want it to be centered, but it's at the bottom of the mat-form-field.

If I adjust the position:absolute values, the problem is, that also when the label goes above the field when a click happens, those rules will be applied as well, moving the floating label in the wrong position.

The code:

<div 
    id="test" 
    fxLayout="row" 
    fxLayoutGap="12px" 
    fxLayoutAlign="start center" 
    [class.hasFocus]="numberMatInput.value">
    <mat-form-field appearance="outline">
         <mat-label>KM</mat-label>
         <input matInput #numberMatInput [formControl]="numberInput">
    </mat-form-field>
</div>

and the CSS:

#test ::ng-deep .mat-form-field-appearance-outline {
  width: 65px;
  height: 45px;
  line-height: 1.725;
}

#test ::ng-deep .mat-form-field-appearance-outline .mat-form-field-flex {
  padding: 0px 10px 0px 10px;
}

#test ::ng-deep .mat-form-field-infix {
  padding: 3px 0 3px 0;
}

this is the wanted result :

enter image description here

so basically I need to move the label when the input field is untouched, and leave it in the same space floating above when it's focused.

to me it seems there is only one rule for both, so if I move the untouched label, the floating one will move as well.

Can someone help? thank you

like image 480
AJ989 Avatar asked Jan 02 '23 22:01

AJ989


1 Answers

Try using the following css:

#test ::ng-deep .mat-form-field-hide-placeholder .mat-form-field-label-wrapper {
   text-align: center;
   top: -25px;
}

#test ::ng-deep .mat-form-field-should-float {
   text-align: center;
}

Demo

like image 117
kboul Avatar answered Jan 05 '23 02:01

kboul