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>

改进后的效果

相关推荐
佛系打工仔16 小时前
绘制K线第二章:背景网格绘制
android·前端·架构
明天好,会的17 小时前
分形生成实验(五):人机协同破局--30万token揭示Actix-web状态管理的微妙边界
运维·服务器·前端
C_心欲无痕18 小时前
nginx - alias 和 root 的区别详解
运维·前端·nginx
我是苏苏20 小时前
Web开发:C#通过ProcessStartInfo动态调用执行Python脚本
java·服务器·前端
无羡仙20 小时前
Vue插槽
前端·vue.js
用户63879947730521 小时前
每组件(Per-Component)与集中式(Centralized)i18n
前端·javascript
SsunmdayKT21 小时前
React + Ts eslint配置
前端
开始学java21 小时前
useEffect 空依赖 + 定时器 = 闭包陷阱?count 永远停在 1 的坑我踩透了
前端
zerosrat21 小时前
从零实现 React Native(2): 跨平台支持
前端·react native