简单的伸缩问题-为什么在不设置伸缩基础的情况下伸缩项目的大小相同

时间:2019-07-26 10:02:29

标签: html css flexbox

我想知道我是否真的正确理解flex-shrinkflex-grow。我试图理解为什么flex子元素的大小不一样。我只希望能够将尽可能多的flex子级(即.flex-item div)添加到包含父级的div中,并让它们调整为彼此相同的宽度。在这种情况下,文本将其中之一推开宽度。

如何在不添加硬编码的flex-basis的情况下解决此问题?

任何解释都将非常有帮助。感谢您的帮助。

#container {
  display: flex;
  justify-content: space-between;
  width: 100%;
  background: pink;
  overflow: hidden; /* words should wrap anyway... */
}
.flex-item {
  border: 1px solid red;
  flex: 0 0 auto; /* should make flex items equal size */
  word-wrap: break-all;
  /* flex-basis: 0; makes flex items too narrow; they should stretch to fill width equally depending on no of flex items inside containing div. Also shouldn't require hard-coding the width */
}
<div id='container'>
  <div class='flex-item'>
    <p>ri bergber gyiruek weeuyrg eir7 gueruygergb e8iygerg ier7 guer y org ery8g e g8e ergerg</p>
  </div>
  <div class='flex-item'>
    <p>ri bergber gyiruew</p>
  </div>
  <div class='flex-item'>
    <p>ri bergber gyiruek wveeuyrg eir7 gueruygergb e8iygerg ier7 guer y org ery8g e g8e ergervwev we wefwew fwef we fwf wek wveeuyrg eir7 gueruygergb e8iygerg ier7 guer y org ery8g e g8e ergervwev we wefwew fwef we fwf wrgber gyiruek wveeuyrg eir7 gueruygergb e8iygerg ier7 guer y org ery8g e g8e ergervwev we wefwew fwef we fwf wek wveeuyrg eir7 gueruygergb e8iygerg ier7 guer y org ery8g e g8e ergervwev we wefwew fwef we fwf wg</p>
  </div>
</div>

Codepen:https://codepen.io/anon/pen/JgRawo

1 个答案:

答案 0 :(得分:1)

只需使用flex: 1属性即可完成此操作,该属性在不同的浏览器上将flex-grow: 1flex-shrink: 1flex-basis的值设置为不同,在Chrome浏览器的0%

通过这种方式,每个元素的大小都相等,并且其内容被包装以匹配其宽度。

使用flex: 0 0 auto的值,您将flex-basis设置为“看我的宽度属性”,这将取决于内容,然后您还说不要缩小或增长。

#container {
  display: flex;
  justify-content: space-between;
  background: pink;
  width: 100%;
}
.flex-item {
  flex: 1;
  border: 1px solid red;
}
<div id='container'>
  <div class='flex-item'>
    <p>ri bergber gyiruek weeuyrg eir7 gueruygergb e8iygerg ier7 guer y org ery8g e g8e ergerg</p>
  </div>
  <div class='flex-item'>
    <p>ri bergber gyiruew</p>
  </div>
  <div class='flex-item'>
    <p>ri bergber gyiruek wveeuyrg eir7 gueruygergb e8iygerg ier7 guer y org ery8g e g8e ergervwev we wefwew fwef we fwf wek wveeuyrg eir7 gueruygergb e8iygerg ier7 guer y org ery8g e g8e ergervwev we wefwew fwef we fwf wrgber gyiruek wveeuyrg eir7 gueruygergb
      e8iygerg ier7 guer y org ery8g e g8e ergervwev we wefwew fwef we fwf wek wveeuyrg eir7 gueruygergb e8iygerg ier7 guer y org ery8g e g8e ergervwev we wefwew fwef we fwf wg</p>
  </div>
</div>