DevPro1993
DevPro1993

Reputation: 58

Is it fine if I use Bootstrap rows as flex containers for its child divs, instead of using columns?

I am new to web development and have been using Bootstrap v4 in my personal projects. As per the grid system mentioned on Bootstrap docs, a row houses columns inside it. I have noticed that Bootstrap row's are flex containers by default and whatever div's I put inside a row behave like flex elements. So they shrink to the content within them.

But if I apply class of col to those divs inside the row, the col divs now fill up the entire row and don't shrink to the size of the content within them. Hence I sometimes prefer to use the child divs within a row without the col class. Also I can directly apply justify-content-center and align-items-center to the row div.

So instead of doing,

<div class="row">
    <div class="col">A</div>
    <div class="col">B</div>
    <div class="col">C</div>
</div>

I prefer to do,

<div class="container">
    <div class="row justify-content-center align-items-center">
          <div>A</div>
          <div>B</div>
          <div>C</div>
      </div>
</div>

Is it a good custom to use rows as flex containers directly or do I have to put columns within them?

I find it difficult to center the content within a column since I end up turning it into a flex container anyways.

Upvotes: 0

Views: 2229

Answers (1)

David Liang
David Liang

Reputation: 21536

In theory, you can use almost anything as flex containers, but .rows in Bootstrap are specially configured as flex containers with negative margins that go well with .col-* classes. Hence I would suggest you stick with this .row and .col-* combinations.

If you want to build a flex container yourself, there are Bootstrap built-in classes you can use, e.g., d-flex, to quickly turn the element into a flexbox.

You can center an element vertically and horizontally if you have the following in its parent:

.parent {
    display: flex;
    justify-content: center;
    align-items: center;
}

And again, there are Bootstrap built-in classes for those as well:

<div class="row">
    <div class="col d-flex justify-content-center align-items-center">
        <p>Your Content</p>
    </div>
</div>

I'm not sure if you think that's quick enough though...

Upvotes: 2

Related Questions