1
votes

I would like to center text in a Material-UI button so that the text is centered irrespective of the icon next to it. At the moment the icon is included in the centering.

The top two buttons in the demo show how it currently looks, I am looking for the text to appear as it does in the bottom two buttons. With the icons before and after these buttons respectively, without influencing the text of the buttons.

Bottom two are desired output

https://codesandbox.io/s/material-demo-forked-tj8ko?file=/demo.js

import React from "react";
import Button from "@material-ui/core/Button";
import { makeStyles } from "@material-ui/core/styles";
import KeyboardArrowRightIcon from "@material-ui/icons/KeyboardArrowRight";
import KeyboardArrowLeftIcon from "@material-ui/icons/KeyboardArrowLeft";

const useStyles = makeStyles((theme) => ({
  button: {
    width: "100%",
    marginBottom: theme.spacing(1),
    marginTop: theme.spacing(1)
  }
}));

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

  return (
    <div>
      <Button
        variant="contained"
        color="secondary"
        className={classes.button}
        startIcon={<KeyboardArrowLeftIcon />}
      >
        Back
      </Button>
      {/* This Button uses a Font Icon, see the installation instructions in the Icon component docs. */}
      <Button
        variant="contained"
        color="primary"
        className={classes.button}
        endIcon={<KeyboardArrowRightIcon />}
      >
        Forward
      </Button>
      <Button variant="contained" color="secondary" className={classes.button}>
        Back
      </Button>
      {/* This Button uses a Font Icon, see the installation instructions in the Icon component docs. */}
      <Button variant="contained" color="primary" className={classes.button}>
        Forward
      </Button>
    </div>
  );
}
1

1 Answers

0
votes

It's possible to move the icons into the inner html of the button and tweak the margins respectively. It's kind of hacky but solves your problem. I forked your demo with the updates: https://codesandbox.io/s/material-demo-forked-xmltd?file=/demo.js

  <Button variant="contained" color="secondary" className={classes.button}>
    <KeyboardArrowLeftIcon style={{ marginLeft: -28 }} />
    Back
  </Button>
  <Button variant="contained" color="primary" className={classes.button}>
    Forward
    <KeyboardArrowRightIcon style={{ marginRight: -28 }} />
  </Button>

You can get the same effect while still using startIcon and endIcon by customizing the styles for the start/end icons using withStyles and then using the resulting customized component:

const CenteredTextButton = withStyles({
  startIcon: {
    marginLeft: -28
  },
  endIcon: {
    marginRight: -28
  }
})(Button);

Edit Button centered text with start/end icon