Material UI (MUI) is a comprehensive collection of prebuilt components that are ready for use in production right out of the box. It is beautiful by design and features a suite of customization options that make it easy to implement your own custom design system. It is an open-source React component library that implements Google's Material Design. In this tutorial, we will be learning how to add spacing between your components using components from MUI.
MUI provides a wide range of shorthand responsive margin and padding utility classes to modify an element's appearance. Follow the below steps to create a new React app and then install MUI package to be able to use its components in our app:
Steps to create a new React app:
Step 1: Type in the following command to create a new React app:
npx create-react-app mui-spacing
Project File Structure: Following is the file structure of the project. All the code will be written in the App.js file:
Step 2: Now move into the directory created and type the following command to install MUI's source files into the React app:
Step 3: To install MUI package using npm:
npm install @material-ui/core
To install MUI package using yarn:
yarn add @material-ui/core
Step 4: Run the react app by typing the command in root of the directory:
To run the React app using npm:
npm start
To run the React app using yarn:
yarn start
Spacing in React MUI: The space utility converts shorthand margin and padding props to margin and padding CSS declarations. Following is the list of the shorthand properties for the property type and side provided by MUI:
The space utility in MUI provides shorthand margin and padding props for the margin and padding properties of CSS. It also provides shorthand props for sides of the container element which helps to set the margin or padding of the element individually for a single side, for a particular direction, or for all sides. The props used for margin and padding properties are m and p respectively while the props for sides are t, b, l, r, x, and y which represent the top, bottom, left, right, horizontal direction, and vertical direction respectively. A combination of margin and padding prop along with a side prop is used to define the spacing relating to the element.
Syntax: {property}{side}: {value}
Refer to the below table for a detailed overview of the margin and padding property combinations along with their sides:
Table for margin properties:
CSS property | prop | Description |
---|
margin | m | This property sets the specified margin from all sides of the element. |
margin-top | mt | This property sets the margin from the top side of the element. |
margin-bottom | mb | This property sets the margin from the bottom side of the element. |
margin-left | ml | This property sets the margin from the left side of the element. |
margin-right | mr | This property sets the margin from the right side of the element. |
margin-left and margin-right | mx | This property sets the specified margin from both the left as well as the right side of the element. |
margin-top and margin-bottom | my | This property sets the specified margin from both the top as well as the bottom side of the element. |
Table for padding properties:
CSS property | prop | Description |
---|
padding | p | This property sets the specified padding from all sides of the element. |
padding-top | pt | This property sets the padding from the top side of the element. |
padding-bottom | pb | This property sets the padding from the bottom side of the element. |
padding-left | pl | This property sets the padding from the left side of the element. |
padding-right | pr | This property sets the padding from the right side of the element. |
padding-left and padding-right | px | This property sets the specified padding from both the left as well as the right side of the element. |
padding-top and padding-right | py | This property sets the specified padding from both the top as well as the bottom side of the element. |
Example:
m // Specifying margin on all sides
pt // Specifying padding-top
ml // Specifying margin-left
py // Specifying padding-top and padding-bottom
Note: The box components can also be centered by setting the margin in the horizontal direction to auto. Moreover, not only use the default numerical values for margin and padding provided by MUI, but we can also specify the margin and padding value in standard CSS units such as px, em, rem, or percentage(%). See the following examples for a better understanding:
Example:
m:4 // Sets margin 4 from all sides
pt:2 // Sets padding-top to the value 2
mx:'auto' // Centering element in the horizontal direction
p:'30px' // Setting the padding in px from all 4 sides
ml:'10%' // Setting margin-left in %
Given Below is an example explaining how to specify the values of margin and padding properties using different units available in MUI:
JavaScript
import Box from "@mui/material/Box";
const App = () => {
return (
<div>
<Box
sx={{
bgcolor: "primary.main",
fontWeight: 700,
height: "150px",
width: "150px",
borderRadius: 2,
fontSize: "1.3rem",
pt: 10,
}}
>
Setting padding top using MUI units
</Box>
<Box
sx={{
bgcolor: "error.main",
fontWeight: 700,
height: "150px",
width: "150px",
borderRadius: 2,
fontSize: "1.3rem",
m: "50px",
}}
>
Setting margin in px
</Box>
<Box
sx={{
bgcolor: "warning.main",
fontWeight: 700,
height: "150px",
width: "150px",
borderRadius: 2,
fontSize: "1.3rem",
px: "15%",
}}
>
Setting padding-x in %
</Box>
<Box
sx={{
bgcolor: "success.main",
fontWeight: 700,
height: "150px",
width: "150px",
borderRadius: 2,
fontSize: "1.3rem",
mx: "auto",
}}
>
Centering the Box horizontally
</Box>
</div>
);
};
export default App;
Output:
Using theme.spacing(): Another way to space components in a React app is to use the theme.spacing() helper. This method helps the user to maintain a uniform spacing all over the UI by specifying a spacing factor and then the value to be multiplied by the factor, the final output will be the product of the spacing factor and the value. The default spacing factor used by MUI is '8px'.
Also, the theme.spacing() helper can be provided by 4 different arguments specifying the values for different sides i.e top, left, bottom, and right in order. Values other than numeric can also be passed. For example: 'auto', '4rem', '20%' .etc.
Example: Given below is an example demonstrating the use of the theme.spacing() helper. It demonstrates how to pass values, multiple values for different sides and values in the form of strings:
JavaScript
import Box from "@mui/material/Box";
import { ThemeProvider, createTheme } from "@mui/material/styles";
const theme = createTheme({
spacing: 8, // Spacing factor
});
const App = () => {
return (
<div>
<ThemeProvider theme={theme}>
{/* Passing multiple values as arguments for
top, right, bottom, left sides in order */}
<Box
sx={{
bgcolor: "error.main",
fontWeight: 700,
height: "150px",
width: "150px",
borderRadius: 2,
fontSize: "1.3rem",
m: theme.spacing(10, 8, 6, 4),
}}
>
This is box 1.
</Box>
{/* Spacing using the theme.spacing()
helper */}
<Box
sx={{
bgcolor: "primary.main",
fontWeight: 700,
height: "150px",
width: "150px",
borderRadius: 2,
fontSize: "1.3rem",
p: theme.spacing(4),
}}
>
This is box 2.
</Box>
{/* Passing values in form of
strings as arguments */}
<Box
sx={{
bgcolor: "warning.main",
fontWeight: 700,
height: "150px",
width: "150px",
borderRadius: 2,
fontSize: "1.3rem",
m: theme.spacing("5%", "auto"),
}}
>
This is box 3.
</Box>
</ThemeProvider>
</div>
);
};
export default App;
Output:
Reference: https://mui.com/system/spacing/
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability.React.jsWhy Use React?Before React, web development faced issues like slow DOM updates
7 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides methods to interact with the Document Object Model, or DOM. This package allows developers to access and modify the DOM. It is a package in React that provides DOM-specific methods that can be used at the top level of a web app to enable an efficient wa
3 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the
5 min read
Components in React
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.Stateless (before hooks)
5 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
4 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects