Bootstrap Spacing Margin and Padding refer to predefined utility classes provided by Bootstrap for managing the spacing around elements. Margin classes control the space outside the element's border, while padding classes control the space inside the border. These classes help in easily adding consistent spacing to elements without writing custom CSS.
Bootstrap 5 Spacing Margin and padding:
- Notations: These are used to choose what styling is to be applied, where the styling is to be applied and the size of the formatting. Basic notation is [property][sides]-[size], and for sm, md, lg, xl, and xxl size screens breakpoints are mentioned before the size to make the webpage responsive. The notation is [property][sides]-[breakpoint]-[size]. Here property can be margin or paddingÂ
- Horizontal Centering: In horizontal centering .mx auto is used for horizontally centering the element by setting the margins to auto on the horizontal side.
Example 1: The following examples, demonstrates the use of margin in bootstrap 5 -
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href=
"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body class="text-center">
<h3>
Bootstrap Margin
</h3>
<div class="container">
<div class="border border-primary" style="height: 300pt;">
<div class="mx-1 my-1 bg-success text-light
d-sm-none p-1">
Grid1
</div>
<div class="mx-2 my-2 bg-success
d-md-none p-1 ">
Grid2
</div>
<div class="mx-3 my-3 bg-success text-light
d-lg-none p-1">
Grid3
</div>
<div class="mx-4 my-4 bg-success d-xl-none p-1 ">
Grid4
</div>
<div class="mx-5 my-5 bg-success text-light
d-xxl-none p-1">
Grid5
</div>
</div>
</div>
</body>
</html>
Output:

Example 2: In this example we use Bootstrap classes to create padding around grid elements, adjusting their width responsively for different screen sizes.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href=
"https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body class="text-center">
<h3>
Bootstrap Padding
</h3>
<div class="container">
<div class="border border-primary"
style="height: 300pt;">
<div class="mx-auto my-1 bg-primary text-light
d-sm-none p-1"
style="width: 100px;">
Grid1
</div>
<div class="mx-auto my-2 bg-primary d-md-none p-1 "
style="width: 200px;">
Grid2
</div>
<div class="mx-auto my-3 bg-primary text-light
d-lg-none p-1"
style="width: 300px;">
Grid3
</div>
<div class="mx-auto my-4 bg-primary d-xl-none p-1 "
style="width: 400px;">
Grid4
</div>
<div class="mx-auto my-5 bg-primary text-light
d-xxl-none py-1"
style="width: 500px;">
Grid5
</div>
</div>
</div>
</body>
</html>
Output:
