【flex-grow】计算 flex弹性盒子的子元素的宽度大小

计算以下两个子div的宽度大小:

代码如下:

复制代码
<!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>
        #div0 {
            width: 400px;
            height: 500px;
            background-color: aqua;
            display: flex;
        }

        #div0 div {
            width: 200px;
            height: 200px;
            background-color: #c01010;
        }
        #div0 div:nth-child(1) {
            flex-basis: 30%;
            flex-grow: 1;
            background-color: blue;
        }

        #div0 div:nth-child(2) {
            flex-basis: 50%;
            flex-grow: 1;
            background-color: rgb(255, 251, 0);
        }
    </style>
</head>

<body>
    <div id="div0">
        <div></div>
        <div></div>
    </div>
</body>

</html>

分析:

对于第一个子元素 div:nth-child(1)

  • 初始宽度为 flex-basis: 30%,即 30% * 400px = 120px。

对于第二个子元素 div:nth-child(2)

  • 初始宽度为 flex-basis: 50%,即 50% * 400px = 200px。

总的剩余空间:

400-120-200=80

因为两个都设置了flex-frow:1,表示会根据剩余空间进行增长

80/2=40 两个平分40

那么第一个子元素的大小为 120+40=160

第二个子元素的大小为200+40=240

因此,根据计算得到,第一个子元素的宽度为约160px,第二个子元素的宽度为约240px。

拓展:

如果一个设置了flex-grow:1 另外一个是flex-grow:2

那么就是80/3=26.67

第一个为120+26.67=146.67

第二个为200+26.67*2=253.34

你学废了嘛?

相关推荐
HelloReader几秒前
Qt 项目构建入门CMake 完全指南(三)
前端
用户908324602737 分钟前
Spring AI + RAG + SSE 实现带搜索来源的智能问答完整方案
前端·后端
GISer_Jing11 分钟前
阿里开源纯前端浏览器自动化 PageAgent,[特殊字符] 浏览器自动化变天啦?
前端·人工智能·自动化·aigc·交互
清风徐来QCQ30 分钟前
js中的模板字符串
开发语言·前端·javascript
成都渲染101云渲染666635 分钟前
Houdini+Blender高效渲染方案(高配算力+全渲染器兼容)
前端·系统架构
SuperEugene1 小时前
Vue3 + Element Plus 表格实战:批量操作、行内编辑、跨页选中逻辑统一|表单与表格规范篇
开发语言·前端·javascript
极梦网络无忧1 小时前
基于 Vite + Vue3 的组件自动注册功能
前端·javascript·vue.js
Predestination王瀞潞1 小时前
5.4.3 通信->WWW万维网内容访问标准(W3C):WWW(World Wide Web) 协议架构(分层)
前端·网络·网络协议·架构·www
爱学习的程序媛2 小时前
【Web前端】优化Core Web Vitals提升用户体验
前端·ui·web·ux·用户体验
zabr2 小时前
花了 100+ 篇笔记,我整理出 了一套 AI Agent 工程完全指南
前端·后端·agent