Dreamy
Dreamy

Reputation: 67

How to center a column in a row?

I was exploring a bit of bootstrap and created a simple row with a column. I set this column to size 4, so it takes up 1/3 of the row.

To center it I used the following code:

<body>

    <div class="container">
        <div class="row align-items-center">
            <div class="col-sm-4" align="center">
                <div>I am here</div>
            </div>
        </div>
    </div>

</body>

However I'm getting the following result, shown in the image below:

enter image description here

Does anyone have an idea of what I am missing/doing wrong. Take you so much in advance :)

Upvotes: 0

Views: 1353

Answers (3)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48590

Use justify-content to center items within a row.

The .row class already displays in flex. Now, all you need to do is tell it how to align its children i.e. justify-content: center. For more on flexbox layout, see: A Complete Guide to Flexbox.

.col-sm-4 {
  border: thin solid red;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row justify-content-center">
    <div class="col-sm-4" align="center">
      <div>I am here</div>
    </div>
  </div>
</div>

Alternatively, you could add a column right before the one in the center, but this is a hack...

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row">
    <div class="col-sm-4"></div>
    <div class="col-sm-4" align="center">
      <div>I am here</div>
    </div>
  </div>
</div>

Upvotes: 1

Joseph
Joseph

Reputation: 6269

There is two way to do that

Old School

You need to add offest class

Pattern

offset-md-*

to be like this

<div class="col-sm-4 offset-md-4" align="center">
   <div>I am here</div>
</div>

New School [Best Practice]

or by just using justifty-content-center like this

  <div class="row justify-content-center">
    <div class="col-sm-4" align="center">
      <div>I am here</div>
    </div>
  </div>

Notice: it would be better to use justifty-content-center class instead of offset

you can read more about offset and flexbox

Upvotes: 0

Francisco
Francisco

Reputation: 1773

Use justify-content-center to center a column in a row.

<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-sm-4">
                <div>I am here</div>
            </div>
        </div>
    </div>
</body>

Upvotes: 0

Related Questions