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>

改进后的效果

相关推荐
zl0_00_08 分钟前
xss-lab
前端·网络·xss
爱上你家菜包14 分钟前
Electron一小时快速上手
前端·javascript·electron
陈琦鹏15 分钟前
Vue3+Vite开发Electron桌面端问题记录
前端·javascript·electron
狼性书生2 小时前
uniapp vue3实现的一款数字动画调节器件,支持长按、单点操作,提供丝滑的增减动画效果
前端·vue.js·微信小程序·小程序·uni-app
Jelena157795857922 小时前
爬虫获取微店商品快递费 item_feeAPI 接口的完整指南
开发语言·前端·爬虫
总是学不会.2 小时前
从“记住我”到 Web 认证:Cookie、JWT 和 Session 的故事
java·前端·后端·开发
xinran_Yi3 小时前
XSS-labs靶场通关
前端·xss
前端代码仔3 小时前
JS继承的几种实现方式
前端·javascript
巅峰赛2000分以下是巅峰3 小时前
buuctf.web 64-96
前端
伶俜Monster3 小时前
Threejs 光照教程,为 3D 场景注入灵魂
前端·3d·webgl·threejs