flex居中布局引起滚动溢出问题

场景

有一个flex布局的容器,item每个都有自己的固定宽度,如果item数量超过一定数值,则这个容器需要出现滚动条,代码如下:

html 复制代码
<div class="wrapper">
    <div>111</div>
    <div>222</div>
    <div>333</div>
    <div>444</div>
    <div>555</div>
</div>
css 复制代码
.wrapper{
  width: 800px;
  background-color: blue;
  display: flex;/*父div设置该属性*/
  overflow-x: scroll;
  justify-content: space-around;
  align-items: center;
}  
.wrapper::-webkit-scrollbar {
  display: none;  
}
.wrapper>div{
  width: 100px;
  height: 50px;
  border: 1px solid black;
  flex-shrink: 0;
}

效果如下:

目前是没问题的,但是当容器宽度变小后,我们期望出现滚动条,结果如下:

js 复制代码
.wrapper{
  width: 200px;  /*修改此处*/
  background-color: blue;
  display: flex;
  overflow-x: scroll;
  justify-content: space-around;
  align-items: center;
}  

chrome下没问题:

在safari上有问题,左侧无法看全,相当于溢出了

问题解决

方法有多种,我看到网上也挺多,我这里主要是多套一层的方式

方式一

多套一层,最外层设置flex布局

html 复制代码
<div class="next-main">
    <div class="next-main-div">
      <div>111</div>
      <div>222</div>
      <div>333</div>
      <div>444</div>
      <div>555</div>
    </div>
</div>
css 复制代码
.next-main {
  width: 200px;
  background-color: salmon;
  display: flex;/*父div设置该属性*/
  overflow-x: scroll;
  justify-content: space-around;
} 
.next-main .next-main-div {
  width: 100%;
  display: flex;
}  
.next-main-div > div {
  width: 100px;
  height: 50px;
  border: 1px solid black;
  flex-shrink: 0;
} 

通过外层多套一个容器,限定好width,当item数量不够时,自然居中,数量多余当前外容器宽度时候,则自动进行滚动,效果如下:

方法二

多套一层容器+inline-flex

inline-flex和flex区别在于inline-flex的外容器会根据内部item进行自动调整

html 复制代码
<div class="next-next-main">
    <div class="next-main-div">
      <div>111</div>
      <div>222</div>
      <div>333</div>
      <div>444</div>
      <div>555</div>
    </div>
</div>
css 复制代码
.next-next-main {
  width: 200px;
  background-color: darkgreen;
  overflow-x: scroll;
} 
.next-next-main .next-main-div {
  display: inline-flex;
  justify-content: space-around;
  align-items: center;
}
.next-main-div > div {
  width: 100px;
  height: 50px;
  border: 1px solid black;
  flex-shrink: 0;
} 

两种方案区别在于flex布局在那一层容器,最终结果都是一样的,第二种方案效果如下

以上就是两种嵌套父级方案了,至于其他方式,大家可以自行去查一下,比如margin: auto

相关推荐
happymaker06262 分钟前
web前端学习日记——DAY01(HTML基本标签)
前端·学习·html
笨笨狗吞噬者6 分钟前
【uniapp】小程序支持分包引用分包 node_modules 依赖产物打包到分包中
前端·微信小程序·uni-app
悟空瞎说16 分钟前
Electron 踩坑实录:主窗口 icon 配置了,打包 Windows 后死活不显示?(全网最细排查+解决方案)
前端
Lee川37 分钟前
Vue Router 4 核心精讲:从原理到面试实战
前端·vue.js
树上有只程序猿40 分钟前
2026年,学“前端”还有前途吗?
前端
我命由我123451 小时前
JS 开发问题:url.includes is not a function
开发语言·前端·javascript·html·ecmascript·html5·js
weixin199701080161 小时前
义乌购商品详情页前端性能优化实战
前端·性能优化
汪啊汪1 小时前
Day 3:Hooks 原理
前端
汪啊汪1 小时前
Day 2:JSX 转换原理
前端
学以智用1 小时前
Vue3 + Vue Router 4 完整示例(可直接运行)
前端·vue.js