Max Koretskyi
Max Koretskyi

Reputation: 105517

why bootstrap's container class has padding while row class has negative margins to compensate the padding

Bootstrap's container class has paddings on both side:

.container-fixed(@gutter: @grid-gutter-width) {
  padding-left:  (@gutter / 2);
  padding-right: (@gutter / 2);
}

While row class has negative margins:

.make-row(@gutter: @grid-gutter-width) {
  margin-left:  (@gutter / -2);
  margin-right: (@gutter / -2);
}

So when we put html like that:

<div class="container">
  <div class="row">
    ...
  </div>
</div>

the content within the row class takes all the space from left to right side of the container offseting the padding using negaive margins. I'm wondering why this approach is used? I've also seen it being used for navbars, specifically navbar-right class has negative margin.

Upvotes: 5

Views: 4449

Answers (2)

Carol Skelly
Carol Skelly

Reputation: 362620

The .container has padding to accommodate the negative margins of the .row, and the .row has negative margins because of the col-* (columns) work. Since columns use padding to create a gutter (space between columns), the row's negative margins eliminate the effect of the padding on the outermost columns.

Without the negative margin, there would be an extra 15 px on the outer sides as you can see here..

https://codeply.com/p/1bLNZAjk8D

Upvotes: 1

Shawn Taylor
Shawn Taylor

Reputation: 15740

Putting your columns in a .row offsets the padding, which is so you can nest columns. Nesting columns is important to have control of some (most) layouts. Since columns have built in padding, if you nest them without offsetting it that padding will multiply and column content won't line up like you want. See this example:

http://www.bootply.com/ZZ4ML0yjSG

<div class="container">
  <h3>Without .row buffer</h3>
  <div class="col-md-12 bg-warning">Column 1
    <div class="col-md-12 bg-danger">
      <div class="col-md-6 bg-info">Nested column 1 without .row buffer</div>
      <div class="col-md-6 bg-success">Nested column 2 without .row buffer</div>
    </div>
  </div>
</div>
<hr>
<div class="container">
  <h3>With .row buffer</h3>
  <div class="row">
    <div class="col-md-12 bg-warning">Column 1
      <div class="row">
      <div class="col-md-12 bg-danger">
        <div class="row">
          <div class="col-md-6 bg-info">Nested column 1 with .row buffer</div>
          <div class="col-md-6 bg-success">Nested column 2 with .row buffer</div>
        </div>
      </div>
  </div>
</div>

Upvotes: 3

Related Questions