情景:父盒子.wrap,子元素.child,實現子元素在父元素中水平和垂直居中css
*{ padding: 0; margin: 0; } body,html{ width: 100%; height: 100%; background-color: #eee; overflow: hidden; } .wrap{ width: 90%; margin: 100px auto; background-color: #fff; height: 400px; } .wrap .child{ width: 200px; height: 200px; background-color: red; }
<body> <div class="wrap"> <div class="child"></div> </div> </body>
方式一:父元素相對定位,子元素絕對定位,margin:autohtml
.wrap{ position: relative; } .child{ position: absolute; left: 0; top: 0; right: 0; bottom: 0; margin: auto; }
方式二:父元素相對定位,子元素絕對定位,margin負一半自身寬高css3
.wrap{ position: relative; } .child{ position: absolute; left: 50%; top: 50%; margin-left: -100px; margin-top: -100px; }
方式三:父元素相對定位,子元素絕對定位,css3位移自身負一半寬高web
.wrap{ position: relative; } .child{ position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); }
方式四:給父盒子使用彈性佈局flexide
.wrap{ display: flex; justify-content: center; //主軸 align-items: center; //附軸 }
方式五:彈性佈局,舊的寫法佈局
.wrap{ display: -webkit-box; -webkit-box-pack:center; -webkit-box-align:center; }