关于css:flex-1-的理解

21次阅读

共计 1473 个字符,预计需要花费 4 分钟才能阅读完成。

flex

flex 根本语法

参考 MDN:[https://developer.mozilla.org…]

须要留神的点

flex-basis 是对于主轴来说,主轴能够是 x 轴,也能够是 y 轴,为了不便行文,默认主轴为 x 轴

  • flex-basis 的优先级比 width 高
  • item 的宽度等于 basic 设置或者 width 设置的值加上残余空间被平分后本人占据那局部的值

比方

 容器宽度等于 700px

item1 flex-grow=2 flex-basic 或者宽度 =100px

item2 flex-grow=1 flex-basic 或者宽度 =200px

item3 flex-basic 或者宽度 =100px(flex-grow 默认等于 0)item1 最终宽度 =(700 - 100 - 200 - 100)/ (1 + 2) * 2 + 100 = 300

item1 最终宽度 =(700 - 100 - 200 - 100)/ (1 + 2) * 1 + 200 = 300

item1 最终宽度 = 100  
  • 设置 flex 属性,不论是用单值语法还是双值语法,会扭转 flex-grow flex-shrink flex-basis 的默认属性

比方

flex: 1;

这个是单值语法:1 代表的是 flex-grow 的值,其余两个值会被省略,被省略的时候,会有默认值

flex-grow: 省略时默认值为 1。(本来默认值为 0)
flex-shrink: 省略时默认值为 1。(本来默认值为 1)
flex-grow: 省略时默认值为 0。(本来默认值为 auto)

所以 flex: 1 等于 flex: 1 1 0,而不是 felx: 1 1 auto

flex 布局能够实现的几个成果

前置筹备工作

<div class="content">
    <div class="item1">item1</div>
    <div class="item2">item2</div>
    <div class="item3">item3</div>
</div>

等分布局

.content {
    display: flex;
    width: 800px;
    height: 100px;
}
.item1 {
    background-color: #eee;
    flex: 1;
}
.item2 {
    background-color: #ccc;
    flex: 1;
}
.item3 {
    background-color: #bbb;
    flex: 1;
}

item1 比 item2 item3 宽度多 200px

.content {
    display: flex;
    width: 800px;
    height: 100px;
}
.item1 {
    background-color: #eee;
    flex: 1 200px;
}
.item2 {
    background-color: #ccc;
    flex: 1;
}
.item3 {
    background-color: #bbb;
    flex: 1;
}

item1 的宽度是 item2 item3 的两倍

.content {
    display: flex;
    width: 800px;
    height: 100px;
}
.item1 {
    background-color: #eee;
    flex: 2;
}
.item2 {
    background-color: #ccc;
    flex: 1;
}
.item3 {
    background-color: #bbb;
    flex: 1;
}

按倍数去调配容器的宽度

.content {
    display: flex;
    width: 600px;
    height: 100px;
}
.item1 {
    background-color: #eee;
    flex: 1;
}
.item2 {
    background-color: #ccc;
    flex: 2;
}
.item3 {
    background-color: #bbb;
    flex: 3;
}
正文完
 0