Bootstrap 5 Spacing Horizontal centering
Last Updated :
30 Nov, 2022
Bootstrap 5 Spacing Horizontal centering is used to balance out the margin on both sides by using the mx-auto class and setting the width of the element. Bootstrap provides us with shorthand margin and padding helpers which are also responsive and they help us to easily design the appearance of our webpage. We can determine how much we want to add the margin or padding by adding a number from 0-5.
Bootstrap 5 Spacing Horizontal centering Class:
- mx-auto: This class sets the display to be in the block and it sets the margin to be equal on both sides of the element to make the element center aligned.
Syntax:
<div class="mx-auto" style="width: value;">
<!-- Centered Elements --!>
</div>
Example 1: The code below demonstrates how we can use the mx-auto class and horizontally center an element:
HTML
<!doctype html>
< html lang = "en" >
< head >
< link href =
rel = "stylesheet"
integrity =
"sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin = "anonymous" >
</ head >
< body class = "m-2" >
< div class = "text-center" >
< h1 class = "text-success" >
GeeksforGeeks
</ h1 >
< strong >Bootstrap 5 Spacing Horizontal centering</ strong >
</ div >
< div class = "container bg-light mt-5" >
< div class = "mx-auto bg-success text-light"
style = "width: 15rem;" >
< p >This div is horizontally centered
< br >Using the mx-auto
</ p >
</ div >
</ div >
</ body >
</ html >
|
Output:
Example 2: The code below demonstrates how we can use the mx-auto class and horizontally center a card group:
HTML
<!doctype html>
< html lang = "en" >
< head >
< link href =
rel = "stylesheet"
integrity =
"sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin = "anonymous" >
</ head >
< body class = "text-center m-2" >
< div >
< h1 class = "text-success" >
GeeksforGeeks
</ h1 >
< strong >Bootstrap 5 Spacing Horizontal centering</ strong >
< div class = "container bg-light mt-5" >
< div class = "card-group mx-auto" style = "width: 30rem;" >
< div class = "card" >
< img src =
class = "card-img-top"
alt = "..." >
< div class = "card-body" >
< h5 class = "card-title" >This is the first Card</ h5 >
</ div >
</ div >
< div class = "card" >
< img src =
class = "card-img-top"
alt = "..." >
< div class = "card-body" >
< h5 class = "card-title" >This is the second Card</ h5 >
</ div >
</ div >
< div class = "card" >
< img src =
class = "card-img-top"
alt = "..." >
< div class = "card-body" >
< h5 class = "card-title" >This is the third Card</ h5 >
</ div >
</ div >
</ div >
</ div >
</ div >
</ body >
</ html >
|
Output:
Reference: https://getbootstrap.com/docs/5.0/utilities/spacing/#horizontal-centering
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...