场景:
使用flex垂直居中对齐,div内的三个盒子长度未知,由内容撑开,超出父盒子宽度后滚动条显示,最左侧盒子内容会显示不全
例:
正常box1盒子应该是红色宽度,用了flex的缘故,只显示了黄色部分,超出部分隐藏了
查看代码:
<div class="center">
<div class="box1">11111111111111111111111111111111111111</div>
<div class="box2">22222222222222222222222222222222222222</div>
<div class="box3">33333333333333333333333333333333333333</div>
</div>
<style>
.center{
border: 1px solid red;
overflow: auto;
margin-left: 100px;
width: 800px;
height: 400px;
display: flex;
align-items: center;
justify-content: center;
}
.center div{
height: 100px;
}
.box1{
background: skyblue;
}
.box2{
background: darkseagreen;
}
.box3{
background: pink;
}
</style>
解决方案:
用inline-flex替代flex,在flex父级再添加一个div盒子,设置最小宽度
修改后
.center{
width: 800px;
border: 1px solid red;
overflow: auto;
margin-left: 100px;
}
.box{
min-width: 800px;
height: 400px;
display: inline-flex;
align-items: center;
justify-content: center;
}
.box div{
height: 100px;
}
.box1{
background: skyblue;
}
.box2{
background: darkseagreen;
}
.box3{
background: pink;
}
</style>
<body>
<div class="center">
<div class="box">
<div class="box1">11111111111111111111111111111111111111</div>
<div class="box2">22222222222222222222222222222222222222</div>
<div class="box3">33333333333333333333333333333333333333</div>
</div>
</div>
</body>
修改后的样式
最左侧完美展示
宽度不超过父盒子宽度时也是居中展示,超过后也能正常显示最初左侧数据
延伸:
flex: 将对象作为弹性伸缩盒显示
inline-flex:将对象作为内联块级弹性伸缩盒显示
代码:
<style>
.mainBox{
background: skyblue;
display: flex; // 父盒子为flex不设置宽度默认是100%显示;父盒子为inline-flex不设置宽度,默认宽度为子盒子撑开的宽度
}
.mainBox>div{
height: 100px;
width: 100px;
border: 1px solid #000;
}
</style>
<body>
<div class="mainBox">
<div>11</div>
<div>22</div>
</div>
</body>