Home > Mobile >  Padding not working for material ui component (button)
Padding not working for material ui component (button)

Time:08-06

I am having an issue with applying padding (and styles) to my Material UI component.

I have this component here:

import "./css/Landing.css";
import { Button } from "@mui/material";

function Landing() {
  return (
    <div className="Background">
      <div className="centerdiv">
        <div>
          <Button className="Login-Button" variant="contained">
            Register
          </Button>
        </div>
        <div>
          <Button variant="contained">Login</Button>
        </div>
      </div>
    </div>
  );
}

export default Landing;

This component references the following CSS file and Login Button Class:

.Background {
    background-color: black;
    background-repeat: no-repeat;
    background-size: cover;
    position: absolute;
    height: 100%;
    width: 100%;
}

.wrapper {
    text-align: left;
    background: gray;
    /* so we can actually see what's happening */
    padding: 20px;
    position: absolute
        /* Give us some breathing room */
}

.centerdiv {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;
    width: 100px;
    height: 100px;
}

.Login-Button {
    background-color: #ffffff;
    padding: 10px;
}

When I attempt to reference the LoginButton class, the padding for my Material UI Button doesn't work. As well as the styles.

What is the best practice way of adding styles to my buttons?

CodePudding user response:

Its probably because the styles inside Button take precedence over yours due to CSS specificity. Probably you can check this by using the dev tools to see if your styles are crossed out.

You need to use the material-ui theming solution: https://mui.com/material-ui/customization/theme-components/

CodePudding user response:

You can create a styled button using 'styled' from MUI

import styled from "@mui/system/styled";
import Button from "@mui/material/Button";

export const LoginButton = styled(Button)(({ variant }) => ({
  ":hover": {
    backgroundColor: "pink"
  },
  border: "solid red",
  backgroundColor: "black",
  width: "200px",
  color: "white",
  padding: "20px",
  boxShadow: "3px 3px 3px pink"
}));

export default function App() {
  return (
    <div>
      <LoginButton variant="boring">LOGIN</LoginButton>
    </div>
  );
}

CodeSandbox : https://codesandbox.io/s/styled-button-variant-mui-sofl-forked-nwyxde?file=/src/StyledButton.js

  • Related