Jai Kumar Rajput
Jai Kumar Rajput

Reputation: 4207

Put columns in center if there are less columns than full row

I'm new to Bootstrap

I have a HTML like:

<div class="row">
  <div class="col-lg-3">
    First Column
  </div>
  <div class="col-lg-3">
    Second Column
  </div>
</div>

Now there are only two columns of 3 size each and will not cover the full length of the row so there will be blank space at the right side of the row on the view.

These columns are dynamic like these may be One, two, three or may be four in a row at a time.

I want this, if there are less then four columns with size 3 in the row, those columns should be in center of the row instead of left side and blank space in right side.

Please suggest, how can I manage this kind of case?

Upvotes: 2

Views: 252

Answers (2)

Rajath Kumar PM
Rajath Kumar PM

Reputation: 655

.row {
   display: flex;
   justify-content: center;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
  <div class="col-lg-3">
        First Column
  </div>
  <div class="col-lg-3">
        Second Column
  </div>
</div>

you can use offset class or just add these css

.row {
    display: flex;
    justify-content: center;
}

Upvotes: 2

Bhuwan
Bhuwan

Reputation: 16855

According to your requirement and if you are just new to bootstrap, I will recommend you to implement bootstrap4, as this framework is based on Flexbox and its very easy to align the columns here

Reference:

.col-3 {
  padding-top: .75rem;
  padding-bottom: .75rem;
  background-color: rgba(86, 61, 124, .15);
  border: 1px solid rgba(86, 61, 124, .2);
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div class="container">
  <div class="row justify-content-center">
    <div class="col-3">1</div>
    <div class="col-3">2</div>
  </div>
</div>


But if you are working in a code that already using bootstrap3 and can't switch to bootstrap4, use a custom class of yours in row and use flexbox

.flex-row {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
}

.flex-row .col-xs-3 {
  padding-top: .75rem;
  padding-bottom: .75rem;
  background-color: rgba(86, 61, 124, .15);
  border: 1px solid rgba(86, 61, 124, .2);
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
  <div class="row flex-row">
    <div class="col-xs-3">1</div>
    <div class="col-xs-3">2</div>
  </div>
</div>

Upvotes: 3

Related Questions