Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

css - What are the differences between flex-grow and width?

I've started using the flexbox recently and there often comes the situation where I need to distribute space on the main axis between elements.

I often hesitate between width and flex-grow. For example, if I want one item to measure 2 measures, and the other 1 measure, adding up to 100%, I have two choices. I can either set width: 66.6% and width: 33.3%, or flex-grow: 2 and flex-grow: 1.

Sometimes if I want one element to grow the rest of the space, I can either do width: 100% or flex-grow: 1.

How do I choose? What are the differences/considerations in using width vs. flex-grow?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

width and flex-grow are two entirely different CSS properties.

The width property is used for defining the width of elements.

The flex-grow property is used for distributing free space in a flex container. This property doesn't apply a specific length to an element, like the width property. It simply allows a flex item to consume whatever space may be available.

Sometimes if I want one element to grow the rest of the space, I can either do width: 100% or flex-grow: 1. How do I choose?

Yes, if there is one element in the row, width: 100% and flex-grow: 1 may have the same effect (depending on padding, border and box-sizing settings).

But what if there are two elements, and you want the second one to take the remaining space? With a sibling in the container, width: 100% causes an overflow. I guess you can do something like this:

width: calc(100% - width of sibling);

But what if the sibling's width is dynamic or unknown? calc is no longer an option.

The quick and easy solution is flex-grow: 1.


While width and flex-grow are apples-to-oranges, width and flex-basis are apples-to-apples.

The flex-basis property sets the initial main size of a flex item and is similar to width.

For the differences between flex-basis and flex-grow see:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...