how to use margin in react mui 5

How to Use Margin in React MUI 5

August 9, 2023 By Aaronn

In this tutorial, we will how to use margin in react with material ui (mui 5). You can use margin prop with any Component using sx props .margin prop can be used with most components, including Box, Typography, TextField, Button, etc.

Install & Setup Vite + React + Typescript + MUI 5


1. react mui 5 margin, margin top, margin left, margin bottom, margin right, margin auto, margin with rem using Box amd sx props.

import { Box, Container } from "@mui/material";

export default function App() {
  return (
    <>
      <Container sx={{ mt: 20 }}>
        <Box sx={{ margin: 20 }}>All Side Margin</Box>
        <Box sx={{ m: 20 }}>Margin</Box>
        <Box sx={{ marginTop: 20 }}>Margin Top</Box>
        <Box sx={{ mt: 20 }}>Margin Top</Box>
        <Box sx={{ marginLeft: 20 }}>Margin Left</Box>
        <Box sx={{ ml: 20 }}>Margin Left</Box>
        <Box sx={{ marginBottom: 20 }}>Margin Bottom</Box>
        <Box sx={{ mb: 20 }}>Margin Bottom</Box>
        <Box sx={{ marginRight: 20 }}>Margin Right</Box>
        <Box sx={{ mr: 20 }}>Margin Right</Box>
        <Box sx={{ mx: 20 }}>Margin Left Right</Box>
        <Box sx={{ my: 20 }}>Margin Top Bottom</Box>
        <Box sx={{ margin: "2rem" }}>Margin Rem</Box>
      </Container>
    </>
  );
}


2. You can also use margin in minus (-).

import { Box, Container } from "@mui/material";

export default function App() {
  return (
    <>
      <Container sx={{ mt: 20 }}>
        <Box sx={{ margin: -20 }}>All Side Margin</Box>
        <Box sx={{ m: -20 }}>Margin</Box>
        <Box sx={{ marginTop: -20 }}>Margin Top</Box>
      </Container>
    </>
  );
}