Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
602 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...