Consider flex-direction
当读到你的问题时,你首先想到的是flex-basis
并不总是适用于width
.
当flex-direction
为row
时,flex-basis
控制宽度.
但是当flex-direction
是column
时,flex-basis
控制高度.
关键区别
以下是flex-basis
和width
/height
之间的一些重要区别:
flex-basis
仅适用于弹性项.Flex容器(也不是Flex项)将忽略flex-basis
,但可以使用width
和height
.
flex-basis
仅在主轴上工作.例如,如果您在flex-direction: column
中,则需要width
属性来水平调整弹性项的大小.
flex-basis
对绝对定位的弹性物品没有影响.需要width
和height
处房产.Absolutely-positioned flex items do not participate in flex layout
By using the flex
property, three properties – flex-grow
, flex-shrink
and flex-basis
– can be neatly combined into one declaration. Using width
, the same rule would require multiple lines of code.
浏览器行为
就它们的渲染方式而言,应该有no difference,介于flex-basis
和width
之间,除非flex-basis
是auto
或content
.
From the spec:
7.2.3. The flex-basis
property个
对于除auto
和content
之外的所有值,flex-basis
的解析方式与水平写入模式中的width
相同.
但auto
或content
的影响可能微乎其微,或者根本没有影响.规格中的更多信息:
auto
在弹性项上指定时,关键字auto
将检索值
作为已用flex-basis
的Main Size属性的.如果该值为
本身为auto
,则使用的值为content
.
content
个
指示根据弹性项的内容自动调整大小.
Note: This value was not present in the initial release of Flexible
Box Layout, and thus some older implementations will not support it.
The equivalent effect can be achieved by using 100 together with a
main size (101 or 102) of 100.
因此,根据规范,flex-basis
和width
解析相同,除非flex-basis
是auto
或content
.在这种情况下,flex-basis
可以使用内容宽度(想必width
属性也会使用).
The flex-shrink
factor
记住Flex容器的初始设置很重要.其中一些设置包括:
flex-direction: row
-flex项目将水平对齐
justify-content: flex-start
-弹性物品将堆叠在主轴上的线条起点
align-items: stretch
-flex项目将扩展到覆盖容器的横向大小
flex-wrap: nowrap
个弹性项目被迫排成一条线
flex-shrink: 1
-弹性物品允许收缩
注意最后一个设置.
因为默认情况下允许收缩弹性项(这可以防止它们溢出容器),所以指定的flex-basis
/width
/height
可能会被覆盖.
例如,flex-basis: 100px
或width: 100px
加上flex-shrink: 1
不一定是flex-basis: 100px
px.
To render the specified width – and keep it fixed – you will need to disable shrinking:
div {
width: 100px;
flex-shrink: 0;
}
或
div {
flex-basis: 100px;
flex-shrink: 0;
}
或, as recommended by the spec:
flex: 0 0 100px; /* don't grow, don't shrink, stay fixed at 100px */
7.2. Components of
Flexibility
鼓励作者使用flex
速记来控制灵活性
而不是直接使用其手写属性,如速记
正确重置所有未指定的组件以容纳common
uses个.
浏览器漏洞
一些浏览器在调整嵌套FLEX容器中的FLEX项的大小时遇到问题.
flex-basis
ignored in a nested flex container. width
works.
使用flex-basis
时,容器会忽略其子项的大小,并且子项会溢出容器.但使用width
属性时,容器会尊重其子对象的大小,并相应地进行扩展.
参考文献:
示例:
flex items using flex-basis
and white-space: nowrap
overflow inline-flex
container. width
works.
在渲染具有white-space: nowrap
的同级项时,设置为inline-flex
的Flex容器似乎无法识别子项上的flex-basis
(尽管它可能只是一个宽度未定义的项).容器不会扩展以容纳物品.
但是当使用width
属性而不是flex-basis
属性时,容器会考虑其子容器的大小,并相应地进行扩展.这在IE11和Edge中不是问题.
参考文献:
示例:
flex-basis
(and flex-grow
) not working on table element
参考文献:
flex-basis
fails in Chrome and Firefox when the grandparent container is a shrink-to-fit element. The set-up works fine in Edge.
与上面链接中的示例一样,涉及position: absolute
,使用float
和inline-block
也会呈现相同的有缺陷的输出(jsfiddle demo).
影响IE 10和11的错误: