How do you get centered content using Twitter Bootstrap?
Assuming gravity is on your side, centering content in Twitter Bootstrap employs the grid system and centering utility classes very well. For horizontal centering, cast your content into .container and .row, then use .justify-content-center or .text-center to realign columns or text respectively. For vertical alignment, slather some .d-flex and .align-items-center within the row. This snippet diagrams these steps:
Use .justify-content-center to center block-level elements horizontally, and blend both .d-flex and .align-items-center to consummate alignment within Bootstrap's responsive gallery.
Block-level Centering
Block-level elements can be centered by auto-magically setting margins to auto. In Bootstrap 4, .center-block class got evicted in favor of utility classes like .mx-auto for horizontal centering and .my-auto for vertical when needed.
Inline and Flex Elements Alignment Techniques
Inline elements? No worries, text-center got your six. For block or flex units with set dimensions, soft-pedal with mx-auto. Emerging flexbox containers? Use .d-flex synchronized with .justify-content-center for horizontal and .align-items-center for vertical alignment.
Mastering Offset Classes
Aligning columns within a row can also employ offset classes like offset-*. However, starting Bootstrap 4, that's about as useful as a screen door on a submarine because you get the modernized flexbox utility classes.
Making it better with specific solutions
Centering Within Fixed Width Elements
When your fixed-width elements act like stubborn kids, settling them down is as easy as setting the left and right margins to auto. This is useful when your content block or image just won't stay dressed in the center of the layout.
Going vertical with centering
Bootstrap 4 grinned mischievously and introduced flex utilities that made vertical alignment a piece of cake. Just apply .align-items-center to a .d-flex row and voila! This is particularly useful when stubborn content refuses to align within hero sections or vertically centered modals.
Responsively scaling centering techniques
Since Bootstrap is a responsive fellow, your centering methods should be the James Bond of different screen sizes. Bootstrap's responsive prefixes (e.g., md, lg) handcuffed to the centering classes should etch alignment across all devices.
Was this article helpful?