核心提示:用弹性布局实现垂直左右居中,以下代码是用弹性布局实现垂直左右居中的例子。!DOCTYPE htmlhtml lang=enheadmeta charset=UTF-8titleDocument/tit...
用弹性布局实现垂直左右居中,以下代码是用弹性布局实现垂直左右居中的例子。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> *{ margin: 0; padding: 0; } .wrap{ width: 100px; height: 100px; border: 1px solid #000; margin: 3.125em auto; display: flex; justify-content: center; align-items: center; } .in{ width: 10px; height: 10px; background: #000; border-radius: 50%; } </style> </head> <body> <p class="wrap"> <p class="in"></p> </p> </body> </html>
其中3.125em=50px;因为em是相对于父容器设置的长度单位,而浏览器默认的字体大小为16px,所以此时1em=16px,即3.125em=3.125 * 16=50px;
display:flex; 设置.wrap为弹性布局
justify-content:center;定义项目在主轴(水平方向)上居中对齐
align-items:center;定义项目在交叉轴(垂直方向)上居中对齐
程序运行结果: