Home > Blockchain >  How do I get Bootstrap to center content so items stay horizontally compact?
How do I get Bootstrap to center content so items stay horizontally compact?

Time:09-29

I have content that I want centered on the page. Inside a div I want items to stay close together (top image), but when the page is resized wider Bootstrap adds space (bottom image) - trying to put them on new column boundaries?

How do I get Bootstrap 5 to keep them compacted to center of page?

This: enter image description here

Instead of this: enter image description here

<div >
    <div >
        <div >
            <div>
                image
            </div>
        </div>
        <div >
            Some texty bits
        </div>
        <div >
            <div>
                image
            </div>
        </div>
    </div>
</div>

CodePudding user response:

Here is an example to reduce the gap between the columns using bootstrap 5.

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div >
  <div >
    <div >
      <div >Custom column padding</div>
    </div>
    <div >
      <div >Custom column padding</div>
    </div>
    <div >
      <div >Custom column padding</div>
    </div>
  </div>
</div>

g- is the space between the columns, and it is known as gutter space. Always set the max width, if you don't want the main containers to span across the devices especially in wider screens

CodePudding user response:

You can use flexbox with Bootstrap's flex utility classes.

You can also use the col-{breakpoint}-auto class in grid to achieve variable width columns.

Solution and demos

https://codesandbox.io/s/bootstrap-flex-example-k7iyn3

With flex:

<div >
  <div >
    <div>
      <img src='https://via.placeholder.com/150'>
    </div>
    <div >
      Some texty bits
    </div>
    <div>
      <img src='https://via.placeholder.com/150'>
    </div>
  </div>
</div>

With grid:

<div className='container'>
  <div className='row gx-0 justify-content-sm-center gap-4'>
    <div className='col col-sm-auto'>
      <img src='https://via.placeholder.com/150' />
    </div>
    <div className='col-sm-auto p-4 bg-info'>Some texty bits</div>
    <div className='col col-sm-auto'>
      <img src='https://via.placeholder.com/150' />
    </div>
  </div>
</div>
  • Related