Prevent flex item from shrinking [duplicate]

2020-03-24 06:27发布

问题:

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:


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?

回答1:

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



回答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