如何使用Flexbox实现页面元素的垂直与水平居中
问题原因
你当前只给外层.voab容器设置了flex居中规则,它的两个子容器.left和.icons本身没有配置内部元素的对齐逻辑,所以内部图片会默认靠左上排列,无法实现居中效果。
解决代码
修改你的CSS为如下内容即可:
/* 清除浏览器默认边距,避免出现多余滚动条 */ * { margin: 0; padding: 0; box-sizing: border-box; } body { background-image: url("_images/back.jpg"); background-attachment: fixed; background-size: cover; background-position: left; background-repeat: no-repeat; height: 100vh; width: 100vw; overflow-x: hidden; } div.voab { height: 100vh; display: flex; } div.left { width: 30%; height: 100%; /* 内部元素水平垂直居中 */ display: flex; justify-content: center; align-items: center; } div.icons { width: 70%; height: 100%; /* 内部元素垂直排列+水平垂直居中 */ display: flex; flex-direction: column; justify-content: center; align-items: center; } .icons img { opacity: 0.6; margin-bottom: 40px; } /* 取消最后一个图标的下边距 */ .icons img:last-child { margin-bottom: 0; }
补充说明
上述代码已经把你写在HTML行内的padding-bottom样式抽离到了CSS中,无需再给每个图标单独写行内样式,后续调整参数更方便。如果不想修改原有HTML结构,保留原来的行内样式也不影响最终布局效果。
内容的提问来源于stack exchange,提问作者vincent
相关产品推荐
相关产品推荐

