273

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:

enter image description hereCodePen: http://codepen.io/anon/pen/RPNpaP.

Any idea what I'm doing wrong?

dipenparmar12
  • 3,042
  • 1
  • 29
  • 39
Science
  • 2,875
  • 2
  • 12
  • 7

3 Answers3

619

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.

Stickers
  • 75,527
  • 23
  • 147
  • 186
  • 2
    The parent has `display: flex;` and the child you want to set the width for has `flex-grow: 0;`, `flex-shrink: 0;` and `width: 300px;// or 20em or what have you` – Pierre May 20 '22 at 14:39
  • @Pierre It can work but not guaranteed. The width can change if sibling items have flex-grow/shrink/basis set. – Stickers Aug 10 '22 at 20:21
  • Why flex doesn't respect width property? – Alex78191 Sep 19 '22 at 16:07
14

In case anyone wants to have a responsive flexbox with percentages (%) it is much easier for media queries.

flex-basis: 25%;

This will be a lot smoother when testing.

// VARIABLES
$screen-xs:                                         480px;
$screen-sm:                                         768px;
$screen-md:                                         992px;
$screen-lg:                                         1200px;
$screen-xl:                                         1400px;
$screen-xxl:                                        1600px;

// QUERIES
@media screen (max-width: $screen-lg) {
    flex-basis: 25%;
}

@media screen (max-width: $screen-md) {
    flex-basis: 33.33%;
}
chris_r
  • 2,039
  • 1
  • 22
  • 22
6

Actually, if you really want to use the width CSS property another workaround for this is to apply this:

.flexbox .red {
  width: 100%;
  max-width: 25em;
}
Mr Washington
  • 1,295
  • 14
  • 15