Introduction
Angular material is powerful library with a lot of features. I guess one of the most usable component is input. I'm sure every project uses forms.
Material design looks good but does not always correspond to our wishes. Pretty often we need to adapt UI to our design. It may not so easy, especially if we are talking about complex components.
In this article, I will show you how you can change material form field and make it looks like a simple field 🙂 When you have label above the field.
Init angular material
I won’t go into detail here. Just use the command and follow instructions:
ng add @angular/material
First step
Before we dive into css we need to do some preparation. We will provide some default options to do it once and forget.
{
provide: MAT_FORM_FIELD_DEFAULT_OPTIONS,
useValue: { appearance: 'outline', floatLabel: 'always' },
},
appearance: 'outline' - to have field with border only
floatLabel: 'always' - to have label always on top
Reduce input height
From my point of view, material field is too big by height. Let's make it a bit smaller. Actually, it's super easy now.
All we need is just set up values for some variables:
.mat-mdc-form-field {
--mat-form-field-container-height: 2.25rem;
--mat-form-field-container-vertical-padding: 0.5rem;
}
You can play with these values and find what fits your needs. As we used built-in variables, position for other elements automatically adjust to it.
Move label
Now, our label is still looking as before. Let's move it above input.
Label positioning is tricky but not for us.
First of all we have to change top property to raise the label higher. We will have to use a few classes for that.
.mat-mdc-text-field-wrapper .mat-mdc-form-field-flex .mat-mdc-floating-label {
top: 8px;
}
Then move it to the far left position. Our field is divided into three sections.
So, we need to set up left property as negative width the first section:
.mat-mdc-text-field-wrapper .mat-mdc-form-field-flex .mat-mdc-floating-label {
top: 8px; // depends on font-sized and your need
left: -12px; // left section width
}
Looks not so good. Our label is cut and part of border is not visible. Let's fix it!
You can reach by change two properties for the same class:
.mat-mdc-notch-piece.mdc-notched-outline__notch {
border-top: solid;
clip-path: none;
}
That's it. Now your Material field visually behaves like a regular text input.
Bonus:
Label shifts when you focus input. It happens because border becomes 2px instead of 1px.
There are two options to solve it.
- change border on focus to 1px
--mat-form-field-outlined-focus-outline-width: 2px;
- change
topproperty for focused input
.mat-mdc-text-field-wrapper.mdc-text-field--focused .mat-mdc-form-field-flex .mat-mdc-floating-label {
top: 7px;
}
Choose your option depending on your needs.




Top comments (0)