Changing font size of floating labels in Material UI v5

Viewed 725

I want to change the font size of the floating labels of input fields in the React lib MUI v5.

I looked this up a year ago when we were still on version 4, and back then the calculation of the cover area behind the label when "floating" seemed to be hard coded, which made it difficult to change it properly with ease.

Is there a proper solution now in v5 that makes for simple adjustments to the floating labels of input fields? A change to fontSize needs to be reflected in the behavior of the label while floating, by also adjusting the white cover area behind the label.

1 Answers

Unfortunately, while there are ways to change the text size of the label, there is no easy way to also adjust the "notch" size when using variant: outline.

Here's what I would do:

  1. Set the font size for the OutlinedInput's notchedOutline class (This sets the width of the notch):
    MuiOutlinedInput: {
      styleOverrides: {
        notchedOutline: {
          fontSize: '2em'
        }
      }
    },
  1. Set the font size for the MuiInputLabel's &.MuiInputLabel-shrink class to match (This sets the shrunken text size):
    MuiInputLabel: {
      styleOverrides: {
        outlined: {
          '&.MuiInputLabel-shrink': {
            fontSize: '2em',
          },
        }
      }
    },

3). (Optional) Also change the transform property on the MuiInputLabel's &.MuiInputLabel-shrink class (this can center the text in the outline line, you'll have to experiment with this and pick a number that works for your font size.):

    MuiInputLabel: {
      styleOverrides: {
        outlined: {
          '&.MuiInputLabel-shrink': {
            fontSize: '2em',
            transform: 'translate(14px, -19px) scale(0.75)'
          },
        }
      }
    },

Note: This is all done with style overrides inside your theme.js (docs: https://mui.com/customization/theme-components/#global-style-overrides)

Related