The Qodesmith
The Qodesmith

Reputation: 3375

How to achieve box-sizing functionality with flexbox?

So I found out the hard way that flexbox doesn't respect the box-sizing: border-box; CSS declaration. Fine. But is there some way to get that functionality using a flexbox layout?

Check out this JS Fiddle. We have 3 rows with 3 boxes in each row. I'd like all the boxes to be the same size. The middle box in the middle row has some margin & border properties making it bigger. In the box model, we would solve that with box-sizing: border-box. Is there some equivalent in the flexbox model?

Live Demo:

$(function() {    
  for(var i = 1; i <= 3; i++) {
    $('<div class="row" id="row' + i + '">').appendTo($('#grid'));
    
    for(var j = 0; j < 3; j++) {
      if(i === 2 && j === 1) {
        $('<div class="box2">').appendTo($('#row' + i));
      } else {
        $('<div class="box">').appendTo($('#row' + i));
      }
    }
  }
});
html {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 300px;
}

body {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100%;
}

#grid {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  border: 25px solid cornflowerblue;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.row {
  width: 100%;
  height: auto;
  margin: 10px;
  box-sizing: border-box;
  border: 1px solid red;
  display: flex;
}

.box {
  flex-grow: 1;
  margin: 10px;
  background: pink;
}

.box2 {
  flex-grow: 1;
  margin: 10px;
  box-sizing: border-box;
  border: 25px solid purple;
  background: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <div id="grid"></div>
</body>

Upvotes: 4

Views: 5598

Answers (1)

Jiayuan
Jiayuan

Reputation: 11

I think you need to define the height in order for the box-sizing to work.

I added height: 25.3%; in the following code, which means (300px-25px*2-10px*6)/((300px-25px*2)*3), and the code works.

http://jiayuanpulto.github.io/test/test_box-sizing.html

Upvotes: 1

Related Questions