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>

改进后的效果

相关推荐
安木夕12 分钟前
C#-Visual Studio宇宙第一IDE使用实践
前端·c#·.net
努力敲代码呀~14 分钟前
前端高频面试题2:浏览器/计算机网络
前端·计算机网络·html
高山我梦口香糖36 分钟前
[electron]预脚本不显示内联script
前端·javascript·electron
神探小白牙36 分钟前
vue-video-player视频保活成功确无法推送问题
前端·vue.js·音视频
Angel_girl3191 小时前
vue项目使用svg图标
前端·vue.js
難釋懷1 小时前
vue 项目中常用的 2 个 Ajax 库
前端·vue.js·ajax
Qian Xiaoo1 小时前
Ajax入门
前端·ajax·okhttp
爱生活的苏苏2 小时前
vue生成二维码图片+文字说明
前端·vue.js
拉不动的猪2 小时前
安卓和ios小程序开发中的兼容性问题举例
前端·javascript·面试
炫彩@之星2 小时前
Chrome书签的导出与导入:步骤图
前端·chrome