How can I center align Material UI Switch and it's icon props?



I’m using Material-UI for a Switch component. This comp has properties for icons. The thing is, when you add icons the alignment is way off.

How can I center align both icons within my Switch?

Check out this sandbox with a replica of the problem:


I don’t think there’s an elegant way to do it in Material-UI 4 (see example at the bottom of the answer).

You can use prop classes to reach the switchBase(.MuiSwitch-switchBase) element, which you want to center. You can do this with makeStyles hook generator, which allows you to override styles:

import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
  yourClass: {
    /* Your styles */

export default function App() {
  const classes = useStyles();

  return (
    <div className="App">
      <Switch classes={{switchBase: classes.yourClass}} />

switchBase element has position: absolute. To center it we can’t use:

top: 50%;
transform: translateY(-50%);

clever method through the implementation of the Switch component.
But we can use:

height: elementHeight;
top: 50%;
marginTop: -elementHeight/2;

You can view the full example below with some additional styles to make it look nicer:

Answered By – Cliff'EmAll

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More