① margin:0 auto;
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> body{margin: 0;} .outer{ width:600px; height:600px; background-color:#D0D0D0; text-align:center; } .inner{ width:300px; height:300px; background-color:#5cb85c; display:inline-block; } </style> </head> <body> <div class="outer"> <div class="inner"> </div> </div> </body> </html>② text-align: center;
.outer{ width:600px; height:600px; background-color:#D0D0D0; text-align:center; } .inner{ width:300px; height:300px; background-color:#5cb85c; display:inline-block; }① 父元素:display:flex; 弹性布局 子元素:align-self:center;设置单个子元素在纵轴上的排列
.outer{ width:600px; height:600px; background-color:#D0D0D0; display:flex; } .inner{ margin:0 auto;//水平居中 width:300px; height:300px; background-color:#5cb85c; align-self:center;//垂直居中 }② display:flex;弹性布局 justify-content: center;设置元素在横轴上的排列 align-items: center;设置元素在纵轴上的排列
.outer{ width:600px; height:600px; background-color:#D0D0D0; display:flex; justify-content: center;//水平居中 align-items: center;垂直居中 } .inner{ width:300px; height:300px; background-color:#5cb85c; }③ 绝对定位和transform
.outer{ width:600px; height:600px; background-color:#D0D0D0; position:relative; } .inner{ width:300px; height:300px; background-color:#5cb85c; position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%);//移动 }④ 绝对定位,并且margin值位auto 此方法不受元素宽高限制
.outer{ width:600px; height:600px; background-color:#D0D0D0; position: relative; } .inner{ width:400px; height:200px; background-color:#5cb85c; position: absolute; margin: auto; left: 0; right: 0; bottom: 0; top:0; }⑤ table-cell属性将元素换成表格样式,再利用表格居中
.outer{ width:600px; height:600px; background-color:#D0D0D0; display: table-cell; vertical-align: middle; } .inner{ margin:0 auto; width:300px; height:300px; background-color:#5cb85c; }