How to Add a Fixed Width Column with CSS Flexbox

Solution with Flexbox

If you want to have a fixed-width column with Flexbox, you need to use the CSS flex or flex-basis property.

First of all, we set the display of our <div> container to "flex". Then, we specify the flex of the "grey" class as "0 0 50px". Here, the first value specifies flex-grow, the second defines flex-shrink, and the last one specifies flex-basis.

For both the "green" and "blue" classes, we set the flex to 1.

Example of setting a fixed-width column with Flexbox:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .flexbox {
        display: flex;
      }
      .grey {
        background: #adadad;
        flex: 0 0 50px;
      }
      .green {
        background: #32c962;
        flex: 1;
      }
      .blue {
        background: #3b66db;
        flex: 1;
      }
    </style>
  </head>
  <body>
    <div class="flexbox">
      <div class="grey">1</div>
      <div class="green">2</div>
      <div class="blue">3</div>
    </div>
  </body>
</html>

Result

1
2
3

We've got a problem here! When the text in <div class="grey">1</div> is longer than the fixed width you've set, it will overflow and mess up the layout of the flexbox.

To fix this, you can add the overflow: hidden; and white-space: nowrap; CSS properties to the .grey class. This will prevent the overflow and keep the text on a single line.

Here's the updated code:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .flexbox {
        display: flex;
      }
      .grey {
        background: #adadad;
        flex: 0 0 50px;
        overflow: hidden;
        white-space: nowrap;
      }
      .green {
        background: #32c962;
        flex: 1;
      }
      .blue {
        background: #3b66db;
        flex: 1;
      }
    </style>
  </head>
  <body>
    <div class="flexbox">
      <div class="grey">Some really long text that should not overflow</div>
      <div class="green">2</div>
      <div class="blue">3</div>
    </div>
  </body>
</html>

Now, even if the text in <div class="grey"> is longer than the fixed width of 50 pixels, it will not overflow and will stay on a single line.