我想知道我是否真的正确理解flex-shrink
和flex-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>
答案 0 :(得分:1)
只需使用flex: 1
属性即可完成此操作,该属性在不同的浏览器上将flex-grow: 1
,flex-shrink: 1
和flex-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>