CSS - flex-basis 属性



CSS flex-basis 属性设置弹性项目在主轴上的初始大小,然后再将剩余空间分配给弹性项目。为了使该属性生效,项目必须是弹性的。

语法

flex-basis: auto | number | initial | inherit;

属性值

描述
auto 长度等于弹性项目的长度。如果项目没有自己的长度,则长度将根据内容确定。默认值。
数值 可以使用长度值 (px, %, em 等) 指定弹性项目的初始长度。
initial 将属性设置为其默认值。
inherit 从父元素继承该属性。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

CSS Flex Basis 属性示例

以下示例说明了使用不同值的 flex-basis 属性。

使用 auto 值的 Flex Basis 属性

为了使弹性项目的大小既可以是特定长度,也可以在没有指定长度的情况下根据其内容自动调整,我们使用 auto 值。这在以下示例中显示。

示例

Open Compiler
<!DOCTYPE html> <html> <head> <style> .container { display: flex; background-color: lightgray; padding: 10px; } .item { color: white; background-color: #4CAF50; border: 1px solid black; padding: 10px; } .item1 { width: 180px; flex-basis: auto; } .item2 { flex-basis: auto; } .item3 { width: 150px; flex-basis: auto; } </style> </head> <body> <h2> CSS flex-basis property </h2> <h4> flex-basis: auto (Item1-180px, Item3-150px) </h4> <div class="container"> <div class="item item1"> Item 1 </div> <div class="item item2"> Item 2 </div> <div class="item item3"> Item 3 </div> </div> </body> </html>

使用长度值的 Flex Basis 属性

可以使用长度值 (例如 10px、20%、30em 等) 设置弹性项目的初始长度。项目的长度将根据指定的值更改。使用百分比的长度值确定相对于容器大小的尺寸。这在以下示例中显示。

示例

Open Compiler
<!DOCTYPE html> <html> <head> <style> .container { display: flex; background-color: lightgray; padding: 10px; } .item { color: white; background-color: #4CAF50; border: 1px solid black; padding: 10px; } .item1 { flex-basis: 200px; } .item2 { flex-basis: 60%; } .item3 { flex-basis: 35em; } </style> </head> <body> <h2> CSS flex-basis property </h2> <h4> flex-basis: Item1-100px, Item2-50%, Item3-45em </h4> <div class="container"> <div class="item item1"> Item 1 </div> <div class="item item2"> Item 2 </div> <div class="item item3"> Item 3 </div> </div> </body> </html>

支持的浏览器

属性 Chrome Edge Firefox Safari Opera
flex-basis 29.0 11.0 28.0 9.0 17.0
css_properties_reference.htm
广告