flex-grow 和 width 有什么区别? [英] What are the differences between flex-grow and width?

查看:35
本文介绍了flex-grow 和 width 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始使用 flexbox,经常出现需要在元素之间的主轴上分配空间的情况.

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.

我经常在 widthflex-grow 之间犹豫.例如,如果我想要一个项目测量 2 个测量值,而另一个测量值加起来为 100%,我有两个选择.我可以设置 width: 66.6%width: 33.3%,或者 flex-grow: 2flex-grow: 1.

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.

有时如果我想要一个元素来扩展其余的空间,我可以使用 width: 100%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.

我该如何选择?使用 width 与 flex-grow 的区别/注意事项是什么?

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

推荐答案

widthflex-grow 是两个完全不同的 CSS 属性.

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

width 属性用于定义元素的宽度.

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

flex-grow 属性用于分配弹性容器中的可用空间.此属性不会将特定长度应用于元素,例如 width 属性.它只是允许 flex 项消耗任何可用空间.

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.

有时如果我想要一个元素来扩展其余的空间,我可以使用 width: 100%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?

是的,如果一行中有一个元素,width: 100%flex-grow: 1 可能效果是一样的(取决于paddingborderbox-sizing 设置).

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).

但是如果有两个元素,并且您希望第二个元素占用剩余空间怎么办?对于容器中的同级,width: 100% 会导致溢出.我想你可以这样做:

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);

但是如果兄弟的宽度是动态的或未知的怎么办?calc 不再是一个选项.

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

快速简便的解决方案是flex-grow: 1.

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

虽然widthflex-grow 是apples-to-oranges,但widthflex-basis 是苹果对苹果.

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

flex-basis 属性设置 flex 项目的初始主尺寸,类似于 width.

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

flex-basisflex-grow 的区别见:

这篇关于flex-grow 和 width 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆