Prevent flex item from shrinking [duplicate]

2020-03-24 06:34发布

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?

标签: html css flexbox
2条回答
地球回转人心会变
2楼-- · 2020-03-24 06:59

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

查看更多
太酷不给撩
3楼-- · 2020-03-24 07: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

查看更多
登录 后发表回答