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

问题

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

示例代码

<!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来实现横向排列,并且不允许盒子换行。

<!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>

改进后的效果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/glorydx/article/details/131934621
今日推荐