yung peso
yung peso

Reputation: 1796

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:

https://codesandbox.io/s/nervous-yalow-z9dev?file=/src/App.js

Upvotes: 1

Views: 1705

Answers (1)

Pet'EmAll
Pet'EmAll

Reputation: 186

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}} />
    </div>
  );
}

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:

https://codesandbox.io/s/zealous-kapitsa-xgkzg?file=/src/App.js

Upvotes: 2

Related Questions