In Bootstrap 4, it is recommended to utilize the text-center
class for aligning inline-blocks.
Keep in mind that using text-align:center;
in a custom class applied to the parent element will be effective regardless of the version of Bootstrap being used, similar to what .text-center
does.
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<div class="container">
<div class="row">
<div class="col text-center">
<button class="btn btn-default">Centered button</button>
</div>
</div>
</div>
If the content that needs to be centered is block or flex (not inline-
), utilizing flexbox for centering is recommended:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<div class="d-flex justify-content-center">
<button class="btn btn-default">Centered button</button>
</div>
This method applies
display: flex; justify-content: center
to the parent element.
Note: Avoid using .row.justify-content-center
over .d-flex.justify-content-center
, as .row
may result in unexpected horizontal scrollbars due to negative margins, unless .row
is directly within .container
which provides padding to counteract the negative margin. If you opt to use .row
, remember to override its margin and padding with .m-0.p-0
to achieve similar styles to .d-flex
.
Important note: When the centered content (e.g. button) exceeds the parent's width (.d-flex
), especially with viewport width containers, it may hinder horizontal scrolling back to the beginning of the content. Avoid this method if the centered content may exceed the parent's width and all content needs to be reachable.