How to set a fixed width column with CSS flexbox

Science picture Science · Apr 27, 2015 · Viewed 172.3k times · Source

CodePen: http://codepen.io/anon/pen/RPNpaP.

I want the red box to be only 25 em wide when it's in the side-by-side view - I'm trying to achieve this by setting the CSS inside this media query:

@media all and (min-width: 811px) {...}

to:

.flexbox .red {
  width: 25em;
}

But when I do that, this happens:

http://i.imgur.com/niFBrwt.png

Any idea what I'm doing wrong?

Answer

Stickers picture Stickers · Apr 27, 2015

You should use the flex or flex-basis property rather than width. Read more on MDN.

.flexbox .red {
  flex: 0 0 25em;
}

The flex CSS property is a shorthand property specifying the ability of a flex item to alter its dimensions to fill available space. It contains:

flex-grow: 0;     /* do not grow   - initial value: 0 */
flex-shrink: 0;   /* do not shrink - initial value: 1 */
flex-basis: 25em; /* width/height  - initial value: auto */

A simple demo shows how to set the first column to 50px fixed width.

.flexbox {
  display: flex;
}
.red {
  background: red;
  flex: 0 0 50px;
}
.green {
  background: green;
  flex: 1;
}
.blue {
  background: blue;
  flex: 1;
}
<div class="flexbox">
  <div class="red">1</div>
  <div class="green">2</div>
  <div class="blue">3</div>
</div>


See the updated codepen based on your code.