为何设置margin:auto无法使div在header中垂直居中?
为什么div无法在header中垂直居中?
你遇到的问题核心在于:margin: auto实现垂直居中的前提是容器启用了弹性布局(flex)或网格布局(grid),或者子元素是绝对定位且容器有定位属性。
你的header是默认的块级元素,没有开启flex/grid,所以给div设置margin: auto 30px时,上下的auto不会生效——普通块级容器不会自动分配剩余空间给子元素的上下margin,自然无法实现垂直居中。
快速解决方案
给header添加flex布局,同时设置垂直对齐属性:
body { margin:0; } header { background-color: #f2f2f2; height: 50px; display: flex; /* 开启flex容器 */ align-items: center; /* 让子元素垂直居中 */ } div { display: flex; justify-content: space-between; margin: 0 30px; /* 上下margin设为0即可,因为header的align-items已经搞定垂直居中 */ width: 100%; /* 确保div占满header的可用宽度,维持space-between的效果 */ }
补充方案(非flex实现)
如果不想用flex,也可以用绝对定位的方式实现,但flex布局是当前处理这类布局最简洁可靠的方案:
header { background-color: #f2f2f2; height: 50px; position: relative; /* 开启相对定位 */ } div { display: flex; justify-content: space-between; position: absolute; top: 0; bottom: 0; left: 30px; right: 30px; margin: auto 0; /* 上下auto生效,实现垂直居中 */ }
内容的提问来源于stack exchange,提问作者G1nd3kk
相关产品推荐
相关产品推荐

