當flex的justify-content遇上overflow
阿新 • • 發佈:2020-12-25
技術標籤:前端實踐justify-contentoverflow
當一個容器中設定了flex的justify-content:center
,並且設定overflow
時,看下面這個程式碼:
<style>
.test{
height:100px;
border:1px solid #559;
overflow:auto;
/** 下面是垂直水平居中 */
display: flex;
flex-direction: column;
align-items:center;
justify-content:center;
}
</style>
<div class="test">
<p>123</p>
<p>456</p>
<p>789</p>
</div>
顯示如下:
居中顯示沒問題,scroll也出現了,但是滾動條在最上面的時候,123被擋住了!!
導致這個的原因就是justify-content:center
,取值為:space-around / space-evenly
時也會有這個問題。
解決辦法
把兩個屬性分開,在列表p外面在套一層
<style>
.test{
height:100px;
overflow:auto;
border:1px solid #559;
}
.box{
display: flex;
flex-direction: column;
align-items:center;
justify-content:center;
}
</style>
<div class="test" >
<div class="box">
<p>123</p>
<p>456</p>
<p>789</p>
</div>
</div>