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. "Hello, World!" Program in ReactJavaScriptimport React from 'react'; function App() {
6 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 DOM-specific methods to interact with and manipulate the Document Object Model (DOM), enabling efficient rendering and management of web page elements. ReactDOM is used for: Rendering Components: Displays React components in the DOM.DOM Manipulation: Al
2 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 ListsIn lists, React makes it easier to render multiple elements dynamically from arrays or objects, ensuring efficient and reusable code. Since nearly 85% of React projects involve displaying data collectionsâlike user profiles, product catalogs, or tasksâunderstanding how to work with lists.To render a
4 min read
React FormsIn React, forms are used to take input from users, like text, numbers, or selections. They work just like HTML forms but are often controlled by React state so you can easily track and update the input values.Example:JavaScriptimport React, { useState } from 'react'; function MyForm() { const [name,
4 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. When rendering a list, you need to assign a unique key prop to each element in th
4 min read
Components in React
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