9

Sample:

#wrap {
  outline: 1px solid fuchsia;
  display: flex;
}

#left {
  background: tan;
  width: 100%;
}

#right {
  background: teal;
  width: 50px;
  height: 50px;
}
<div id="wrap">
  <div id="left"></div>
  <div id="right"></div>
</div>


Screenshot:

enter image description here


Questions:

  1. When I use the browser element inspector, I see the right box is less than 50px wide although it has a fixed width in the CSS. Why does it basically happen?
  2. How can it be prevented?
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701

2 Answers2

16

You can also use flex-shrink: 0; on the #right element to prevent it from shrinking.

This just defines that the #right element should not be allowed to shrink e.g. stays at 50px.

For more informations about flex there are many good articles e.g. on css-tricks

Stefan F.
  • 608
  • 7
  • 15
2

Use flex: 1 1; on #left instead of width:100%

#wrap {
  outline: 1px solid fuchsia;
  display: flex;
}

#left {
  background: tan;
  flex: 1 1;
}

#right {
  background: teal;
  width: 50px;
  height: 50px;
}
<div id="wrap">
  <div id="left"></div>
  <div id="right"></div>
</div>

flex: <positive-number>

Equivalent to flex: 1 0. Makes the flex item flexible and sets the flex basis to zero, resulting in an item that receives the specified proportion of the free space in the flex container. If all items in the flex container use this pattern, their sizes will be proportional to the specified flex factor.

Source

Abhishek Pandey
  • 13,302
  • 8
  • 38
  • 68
  • What if I don't use the `flex` property? Can I still have a `50px` × `50px` box while using `width:100%`? –  Apr 12 '17 at 06:00
  • @Mike The proper use of `flexbox` would be to set `flex: 1` on the `left` element. If to keep the `width: 100%`, set `flex-shrink: 0` on the `right`, as _Stefan F._ suggested in his answer. – Asons Apr 12 '17 at 09:07