<div class="container"></div>
.container{ margin:0 auto; }
.container{ width: 150px; position: absolute; left: 50%; margin-left: -50px; border: 1px solid red; }
.container { position: absolute; left: 50%; top: 50%; transform: translate3d(-50%, -50%, 0); }
<div class="container"> <div class="sub-container"></div> </div>
.container{ width:200px; height:100px; position: absolute; top:50%; left:50%; } .sub-container{ width:100%; height:100%; margin-top:-50%; margin-left:-50%; }
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no,minimal-ui"> <title></title> <style> * { padding:0; margin:0; } html,body { height:100%; } .demo { width:100px; height: 100px; text-align: center; line-height: 100px; background:lightblue; } .demo-1 { position: absolute; margin:0 auto; left:0; right:0; } .demo-2 { position: absolute; margin:auto 0; top:0; bottom:0; } .demo-3 { position: absolute; margin:auto; top:0; bottom:0; left:0; right:0; } </style> </head> <body> <div class="demo demo-1">水平居中</div> <div class="demo demo-2">垂直居中</div> <div class="demo demo-3">中心居中</div> </body> </html>
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no,minimal-ui"> <title></title> <style> * { padding:0; margin:0; } html,body { height:100%; } .demo { width:100px; height: 100px; text-align: center; line-height: 100px; background:peachpuff; } .demo-1 { position: absolute; left:50%; -webkit-transform:translateX(-50%); } .demo-2 { position: absolute; top:50%; -webkit-transform:translateY(-50%); } .demo-3 { position: absolute; top:50%; left:50%; -webkit-transform:translateX(-50%) translateY(-50%); } </style> </head> <body> <div class="demo demo-1">水平居中</div> <div class="demo demo-2">垂直居中</div> <div class="demo demo-3">中心居中</div> </body> </html>
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no,minimal-ui"> <title></title> <style> * { padding:0; margin:0; } html,body { height:100%; } .demo { width:100px; height: 100px; text-align: center; background:lightblue; } .demo-1 { position: absolute; margin: 0 auto; left: -88px; right: 0; } .demo-2 { position: absolute; margin: auto 0; top: -30px; bottom: 0; } body:before { content: ''; width: 100%; border-bottom: 2px dotted blue; position: absolute; top: 50%; -webkit-transform: translateY(-2px); } body:after { content: ''; height: 100%; border-left: 2px dotted blue; position: absolute; left: 50%; -webkit-transform: translateX(2px); } </style> </head> <body> <div class="demo demo-1">水平 距離偏移</div> <div class="demo demo-2">垂直 距離偏移</div> </body> </html>