Explain Codes LogoExplain Codes Logo

Align two divs horizontally side by side center to the page using Bootstrap CSS

html
responsive-design
grid-system
css
Anton ShumikhinbyAnton Shumikhin·Oct 16, 2024
TLDR

Align and center two divs side by side in Bootstrap by placing them inside a .container and a .row, and using .col or .col-auto for equal or content-width-based sizing, respectively. Use .justify-content-center for horizontal centering.

<div class="container"> <div class="row justify-content-center"> <div class="col"> <!-- First div (if lost, please return to owner) --> </div> <div class="col"> <!-- Second div (reward if found) --> </div> </div> </div>

This layout applies Bootstrap's grid system for horizontally aligning and centering divs with responsiveness across varying window sizes.

Grid sizing for responsive design

Bootstrap provides grid classes (col-sm-*, col-md-*, etc.) for different screen sizes. For optimal desktop and mobile responsiveness without extra media queries, use col-md-6 and col-6 to produce two half-width columns side by side.

<div class="container"> <div class="row justify-content-center"> <div class="col-6 col-md-6"> <!-- First div (smells like clean code) --> </div> <div class="col-6 col-md-6"> <!-- Second div (contains traces of humor) --> </div> </div> </div>

Offset for fine control

Bootstrap’s offset classes (col-md-offset-*) deliver precise alignment by creating extra space on a column's left side. Here's an example:

<div class="container"> <div class="row justify-content-center"> <div class="col-md-4 col-md-offset-2"> <!-- First div (finding me is a two-column offset task) --> </div> <div class="col-md-4"> <!-- Second div (Im just four columns wide, nice to meet you!) --> </div> </div> </div>

This offsets the first div by two columns, centering the two divs on the page.

Centre of attention: Advanced flex utilities

Bootstrap 4 leverages flex utilities for advanced alignment. Use d-flex and justify-content-center to center items both horizontally and vertically.

Multiple column classes for responsiveness

Using multiple col-* classes tailors responsiveness for different screen sizes. col-xx for general responsiveness and col-lg, col-md, col-sm, col-xs for specific breakpoints.

<div class="container"> <div class="row justify-content-center"> <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6"> <!-- First div (I'm flexible, just like my yoga instructor!) --> </div> <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6"> <!-- Second div (Oh look, I fit right next to the first one!) --> </div> </div> </div>

This responsive design, achieved with Bootstrap container and column classes, provides a clean, maintainable codebase.

When .center-block isn't your friend

.center-block in Bootstrap 3 doesn't play well with grid elements. Bootstrap 4 uses flex utilities for alignment, not .center-block.