Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mui function to change color to either black or with in regard to blackground color

I was wondering which function can i use from material ui to get its characteristic property of changing text color to either white or black in regard of blackground color, if bg is dark it changes color to white and if bg is light it changes color to black. exmaple

<AppBar color="primary">
     <Toolbar>
         <Typography color="inherit" > some text </Typography>
     </Toolbar>
</AppBar>

now somehow if my primary color is a dark color MUI will automatically change my text color to white, and for light color will change to black.

which function or anything basically i can use to accomplish this functionality.

i tried a css property

mix-blend-mode: "difference"

but it doesn't give black/white like in MUI, It just gives a color with contrast that makes it visible.

like image 340
zOthix Avatar asked Oct 27 '25 07:10

zOthix


1 Answers

Two options:

  1. You can try using Material-UI's built-in getContrastColor method, as in:
<AppBar color="primary">
     <Toolbar>
         <Typography sx={{color: theme.palette.getContrastText("YourColorHere")}}>
           some text 
         </Typography>
     </Toolbar>
</AppBar>

  1. Or you can use mix-blend-mode: "difference" combined with color: "white" (and, optionally, wrap this in a parent div which has filter: "grayscale(1)"). See this example.
like image 167
Jesse Avatar answered Oct 28 '25 23:10

Jesse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!