• 说说 flex-shrink 属性的规则


    问题

    面试题:你能说说 flex-shrink 么?

    我们所知 flex 语法如下

    flex: <flex-grow> <flex-shrink> <flex-basis>
    

    并且可以有一些缩写

    flex: 1
    
    # 等效于
    
    flex: 1 0 0
    

    其中 flex-grow 比较好理解,但是 flex-shrink 关注的就比较少了,正好笔者面试时被问到,一时间想不起来,就查一查并做个笔记

    分析

    先看一段代码,摘录自 MDN

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            #content {
                display: flex;
                 500px;
            }
    
            #content div {
                flex-basis: 120px;
            }
    
            .box { 
                flex-shrink: 1;
            }
    
            .box1 { 
                flex-shrink: 2; 
            }
        </style>
    </head>
    <body>
        <p>the width of content is 500px, flex-basic of flex item is 120px.</p>
        <p>A, B, C are flex-shrink:1. D and E are flex-shrink:2</p>
        <p>the width of D is not the same as A's</p>
        <div id="content">
        <div class="box" style="background-color:red;">A</div>
        <div class="box" style="background-color:lightblue;">B</div>
        <div class="box" style="background-color:yellow;">C</div>
        <div class="box1" style="background-color:brown;">D</div>
        <div class="box1" style="background-color:lightgreen;">E</div>
        </div>
    </body>
    </html>
    

    他的效果是这样的

    为什么 A、B、C 元素写了 flex-shrink: 1; 占 105 px,而 D、E 元素 flex-shrink: 2; 占 91px?

    给出收缩公式

    子项收缩宽度 = 子项收缩比例 * 溢出宽度
    子项收缩比例 = (子项宽度 * 子项flex-shrink) / 所有(子项的宽度 * flex-shrink系数)之和
    

    代入公式,计算 A 的宽度,

    // 有 3 个 A 一样的权重和宽度,有两个 E 一样的权重和宽度
    所有(子项的宽度 * flex-shrink系数)之和 = (120 * 1 * 3 + 120 * 2 * 2) = 840
    
    子项收缩比例 = (120 * 1) / 840 = 0.142857
    
    // 子项目本应该占 120 * 5 的宽度,但父容器只有 500,相减得溢出宽度。
    溢出宽度 = ( 120 * 5 - 500) = 100
    
    子项目收缩宽度 = 0.142857 * 100 = 14.2857
    
    A 的真实宽度为 = 120 - 14.2857 = 105.72px
    

    那么 E 的宽度计算规则类似

    子项收缩比例 = (120 * 2) / 840 = 0.285714
    子项目收缩宽度 = 0.285714 * 100 = 28.5714
    E 的真实宽度为 = 120 - 28.5714 = 91.4286
    
  • 相关阅读:
    (绝对有用)iOS获取UUID,并使用keychain存储
    宏定义判断设备是否是iphone5
    如何在未越狱iOS设备上安装IPA
    制作iOS Ad-Hoc测试应用
    UIWebView中Html中用JS调用OC方法及OC执行JS代码
    ios开发入门- plist 文件读写
    [iOS] 如何将你的程序打包成ipa
    《网络对抗技术》Exp1 PC平台逆向破解——20181308邵壮
    公文传输系统冲刺总结——Day3
    MyOD实验 20181308
  • 原文地址:https://www.cnblogs.com/everlose/p/12937262.html
Copyright © 2020-2023  润新知