3

Sizing to border-box, so that I can give my grid some gutters, but it surprisingly didn't fit into the row any more, even though the columns span 12 rows altogether. I actually thought that setting the box-sizing to border-box will add up both padding, margin and border to the set width and height.

               <div class="row>
                    <div class="col-6"></div>
                    <div class="col-4"></div>
                    <div class-"col-2"></div>
              </div>

               [class*="col-"] {
                padding: 15px;
                margin: 5px;
                float: left;
               }
               * {
                  box-sizing: border-box;
              }

How can I give my grid some gutters?

4lackof
  • 1,250
  • 14
  • 33
pedroyanky
  • 323
  • 2
  • 10
  • `border-box` works for padding, for margin you have to subtract it from the width like `width:calc(100% - 10px)` – Amin Jafari Sep 18 '16 at 06:03
  • 1
    There would be a problem with `margin-box` in that margins collapse vertically. For example, a 10px block with 10px margins by itself would be 30px high. But if it was followed by a block with 15px margins, the bottom margin effectively becomes 15px, so the margin-box would now be 35px high! This is difficult to do coherent calculations with. – Mr Lister Sep 18 '16 at 06:51
  • 1
    @Mr Lister: And, to make matters worse, implementations don't actually resize margins when collapsing, so the margin-box dimensions would not change, which may or may not be what the author expects. [dbaron suggested making margin-box behave like padding-box (or border-box) as a workaround](https://lists.w3.org/Archives/Public/www-style/1999Oct/0083.html), but obviously it's not a very clean solution. – BoltClock Sep 18 '16 at 09:29
  • @BoltClock Yeah, that's a terrible suggestion! Almost as counter-intuitive as letting vertical margins in percentages be based on the width. – Mr Lister Sep 18 '16 at 09:38

1 Answers1

1

Since box-sizing doesn't include margin, here is a simple way (this is also how bootstrap etc do to make it work)

* {
  box-sizing: border-box;
}
[class*="col-"] {
  padding: 15px;
  margin: 5px;
  float: left;
}
.col-6 {
  width: calc(50% - 10px);
}
.col-4 {
  width: calc(33.33% - 10px);
}
.col-2 {
  width: calc(16.67% - 10px);
}

/*  for styling this sample  */
.row div {
  border: 1px solid;
  padding: 20px;
}
<div class="row">
  <div class="col-6"></div>
  <div class="col-4"></div>
  <div class="col-2"></div>
</div>
<div class="row">
  <div class="col-2"></div>
  <div class="col-4"></div>
  <div class="col-2"></div>
  <div class="col-4"></div>
</div>
Asons
  • 84,923
  • 12
  • 110
  • 165