39

I am trying to acheive a flexbox with two columns, the left that is of a fixed width and the right that scales as the page size is altered. For example:

<style>
    .flex_container {
        display: flex;
        width: 100%;
    }

    .flex_col_left {
        width: 200px;
    }
    .flex_col_right {
        width: 85%;
    }
</style>

<div class = "flex_container">
    <div class = "flex_col_left">
        .....
    </div>
    <div class = "flex_col_right">
        .....
    </div>
<div>

This works to an extent but it does not feel right as I am mixing px and %. Is it incorrect to do it this way and if so what might be a better solution?

EDIT Classes naming issue was a typo and now fixed.

RGriffiths
  • 5,722
  • 18
  • 72
  • 120

2 Answers2

68

Instead of setting width in % on right column you can just use flex: 1 and it will take rest of free width in a row.

.flex_container {
  display: flex;
  width: 100%;
}
.flex_item_left {
  width: 200px;
  background: lightgreen;
}
.flex_item_right {
  flex: 1;
  background: lightblue;
}
<div class="flex_container">
  <div class="flex_item_left">
    .....
  </div>
  <div class="flex_item_right">
    .....
  </div>
  <div>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • Perfect - thanks. And this fixes it not showing correctly in IE11 too. Fantastic! – RGriffiths Jan 10 '17 at 11:53
  • For anyone trying to get this to work on the older Flexbox spec (in my case the stock Android 4.3 browser), you'll have to use `-webkit-box-flex: 1` instead of `flex: 1` (and a few other changes), example here: https://www.w3schools.com/code/tryit.asp?filename=FOTB9PW8ZJ8X – Liron Yahdav Feb 25 '18 at 19:39
5

You can use flex-grow: 1 on the non-fixed-width element to allow it to grow (and no width setting).

.flex_container {
  display: flex;
  width: 100%;
}
.flex_item_left {
  width: 200px;
  background: #fa0;
}
.flex_item_right {
  background: #0fa;
  flex-grow: 1;
}
<div class="flex_container">
  <div class="flex_item_left">
    .....
  </div>
  <div class="flex_item_right">
    .....
  </div>
  <div>
Johannes
  • 64,305
  • 18
  • 73
  • 130