flex布局子元素垂直居中,当子元素超过容器大小后,不能通过滚动条滚动到顶端
问题
Flexbox实现居中非常容易。
通过简单的应用align-items: center
,并justify-content: center
以柔性容器,你的Flex-item将垂直和水平居中。
但是,当flex-item大于flex容器时,此方法存在问题。
正如问题所指出的,当flex项溢出容器时,顶部将变得不可访问。
解决方案
要解决此问题,请使用flexbox自动边距,而不是justify-content。
使用auto
边距,可以将溢出的flex项目垂直和水平居中,而不会丢失对其任何部分的访问权限。
因此,不是在flex容器上使用以下代码:
#flex-container { align-items: center; justify-content: center; }
而是在flex-item上使用以下代码:
.flex-item { margin: auto; }
效果演示
运行代码<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>flex布局子元素垂直居中小BUG-www.tonjay.com</title> <style> body { font-family: Arial, Helvetica, sans-serif; } .flex { display: flex; border: 2px solid #ccc; border-radius: 3px; width: 400px; margin: 20px auto; overflow-y: auto; height: 200px; text-align: center; } .flex-item { margin: auto; background: #fafafa; border-radius: 3px; padding: 0 20px; } </style> </head> <body> <div class="flex"> <div class="flex-item"> <p>less tonjay start</p> <p>less tonjay</p> <p>less tonjay end</p> </div> </div> <div class="flex"> <div class="flex-item"> <p>more tonjay start</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay</p> <p>more tonjay end</p> </div> </div> </body> </html>