Flex-grow not working as expected (flex items don't have the widths I expect)

你离开我真会死。 提交于 2019-12-17 21:32:36

问题


JSFiddle

I'm trying to use flex CSS properties to fit a set of elements into a neat little box.

It looks exactly how I want it in IE10, but Chrome shows it very different. I basically have:

  • Container
    • Select box (flex:5), should be about wide enough to show the D, but not much wider.
    • Text input (flex:10), should take up a little more than half the width of the contains
    • Confirm button (flex:6), should be wide enough to contain its text, but not much more.

It works fine in IE, but in Chrome the first two elements take up 50% of the width each, leaving the confirmation button falling off the end.

Is my Flex logic wrong, or is Chrome messing up?


回答1:


The flex-grow portion of the flex property (the first number) determines how the extra space should be distributed between the flex elements when their combined size is smaller than their flex container. The extra space is divided like so: [flex-grow value] / [sum of flex-grow values for all siblings]

  • Text input: 10 / 21
  • Select box: 5 / 21
  • Confirm button: 6 / 21

This extra space is added to the element's size along the main axis to determine its final size. It is not used to determine how large the element is in relation to its flex container, that's what the flex-basis and/or width/height value when set to a percentage is for.

When the combined size of the flex elements is larger than its container, the flex-shrink portion of the flex property (the 2nd unitless value) comes into play. It is basically the reverse of flex-grow: the ratios are the same, but the overflow size is subtracted from the flex item instead of added.

Opera has a very nice explanation of this property in their Flexbox basics article: http://dev.opera.com/articles/view/flexbox-basics/

For your particular problem, I was able to solve it in Chrome by setting the width of the input element to a very small value:

http://jsfiddle.net/JTEhW/2/

input {margin:0; width: 20px}

This solution does not appear to work in Opera if you add the unprefixed properties. It probably won't work in Firefox either. It also makes the elements too small to be usable for non-Flexbox browsers.



来源:https://stackoverflow.com/questions/15927302/flex-grow-not-working-as-expected-flex-items-dont-have-the-widths-i-expect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!