flex盒子 center排布,有滚动条时,拖动滚动条无法完整显示内容

文章目录

问题

最近在开发项目的过程中,发现了一个有趣的事情,与flex盒子有关,不知道算不算是一个bug,不过对于开发者来说,确实有些不方便,感兴趣的同学不妨也去试试。

示例代码

javascript 复制代码
<!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>
        body {
            background-color: #fff;
        }
    </style>
</head>

<body>
    <div class="flex">
        <div class="flex-content-item">simpledengxi</div>
        <div class="flex-content-item">simpledengxi</div>
        <div class="flex-content-item">simpledengxi</div>
        <div class="flex-content-item">simpledengxi</div>
        <div class="flex-content-item">simpledengxi</div>
        <div class="flex-content-item">simpledengxi</div>
    </div>
</body>
</html>

<style>
    .flex {
        display: flex;
        width: 150px;
        overflow: auto;
        justify-content: center;
        background: yellowgreen;
        margin: 0 auto;
    }

    .flex-content-item {
        padding: 20px;
    }
</style>

示例效果

滚动条已经拉到了最左边,但是左边的内容并没有完整显示。

目前flex盒子会出现这个问题的原因无从知晓,只有当以下条件同时满足时,才会这样:display: flex; justify-content: center; 有与flex-direction方向一致的滚动条出现;

解决问题

为了解决显示不完全的问题,我只能放弃使用flex盒子,通过display:inline-block来实现横向排列,并且不允许盒子换行。

javascript 复制代码
<!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>
        body {
            background-color: #fff;
        }
    </style>
</head>

<body>
    <div class="flex">
        <div class="flex-content-item">simpledengxi</div>
        <div class="flex-content-item">simpledengxi</div>
        <div class="flex-content-item">simpledengxi</div>
        <div class="flex-content-item">simpledengxi</div>
        <div class="flex-content-item">simpledengxi</div>
        <div class="flex-content-item">simpledengxi</div>
    </div>
</body>

</html>

<style>
    .flex {
        width: 150px;
        /* 还是优先中间排布 */
        text-align: center;
        background: yellowgreen;
        margin: 0 auto;
        /* 仍然需要滚动条 */
        overflow: auto;
        /* 不允许字体换行,这样就必定会出现滚动条 */
        word-break: keep-all;
        white-space: nowrap;
    }

    .flex-content-item {
        padding: 20px;
        /* 里面的盒子必须是inline-block或者inline 否则 text-align: center 不生效 */
        display: inline-block;
    }
</style>

改进后的效果

相关推荐
不可能片场13 小时前
Electron 发布 正文写入的三条通道与读回口径
前端·electron
jerrywus13 小时前
让 AI 帮你部署 Vercel,报错了也不用手动搬日志
前端·agent·mcp
补码缩写13 小时前
11 行 Python 拆 PNG 块,解压后的字节数能手算
前端
coding漫漫长路13 小时前
PNG压缩先看图是哪一类,先无损再量化多半白做
前端
用户2576807632113 小时前
搜「洗牙」为什么搜不到「洁治」
前端
费曼学习法13 小时前
Agent 死循环的根因不在模型:错误分类、退避、熔断、快照四层实现
前端
修炼的dance13 小时前
同一张PNG换五种压法,体积差在颜色数上
前端
Lank_M13 小时前
PNG 有损压缩省下的体积,大头不在 deflate
前端
用户老李14 小时前
相机模型与标定自学教程 02:外参 \[R | t] 与完整投影链路
前端
用户老李14 小时前
无线电自学教程 03:电路基础——从欧姆定律到 LC 谐振
前端