Explain Codes LogoExplain Codes Logo

How to center content in a Bootstrap column?

html
responsive-design
css
flexbox
Alex KataevbyAlex Kataev·Oct 13, 2024
TLDR

Use Bootstrap's d-flex justify-content-center align-items-center inside your column to center content horizontally and vertically:

<div class="col d-flex justify-content-center align-items-center"> <div>Your content</div> <!-- I'm no longer lost in the space of a column! --> </div>

The d-flex class transforms the column into a flex container, while justify-content-center and align-items-center align the content smack in the center along both axes.

Centering text

For text content, the text-center class is your tool of choice for horizontally centering:

<div class="col text-center"> <p>I used to feel left out, but now I'm in the spotlight! 😎</p> </div>

Working with smaller columns

Teeny-tiny columns like col-xs-1, which sets column widths to a minimal 8.33%, call for an articulate mix of centering techniques:

<div class="col-xs-1 d-flex justify-content-center"> <div>Dieting made me 8.33% thin! But, flex makes sure I'm still noticeable</div> </div>

The justify-content-center addition ensures that your content doesn’t shy away to the corner!

Avoiding historical relics

In the world of modern HTML5, the align attribute sleeps with the dinosaurs. Swear by CSS and Bootstrap classes and avoid using outdated align for centering.

Perfecting complex centering

For those intricate operations that need text within flex items aligned too, mix up d-flex, justify-content-center, and text-center classes:

<div class="d-flex justify-content-center"> <div class="text-center"> <p>I'm not just another Flex-item. I'm the Center of Attention! 🌟</p> </div> </div>

Custom flexbox dance

Sometimes, Bootstrap's pre-defined moves might not fit the groove. In such scenarios, let flexbox take the stage with custom classes and properties like my-auto and flex-direction:

.custom-center { display: flex; flex-direction: column; justify-content: center; height: 100vh; // You control the dance floor with custom height! }

Controlling the uncontrollable

To control content that might burst out of the boundaries, like jabbering text or balloon-sized images, CSS property word-break: break-all; can keep things neat:

.break-content { word-break: break-all; // A traffic cop for your overflowing content! }