方案一(最佳方案):
<!DOCTYPE HTML> <html> <head> <title>test</title> <meta charset="utf-8"> <style> #demo{ width:300px; height:300px; position: relative; background-color: #ff6600; } #indemo{ width:100px; height:100px; position: absolute; left:0;right:0;top:0;bottom:0; margin:auto; background-color: white; } </style> </head> <body> <div id = 'demo'> <div id = 'indemo'></div> </div> </body> </html>
方案二(该方案必须已知indemo的宽度和高度):
#demo{ width:300px; height:300px; position: relative; background-color: #ff6600; } #indemo{ width:100px; height:100px; position: absolute; left:50%; top:50%; margin-left: -50px; margin-top: -50px; background-color: white; }
方案三(不使用定位):
#demo{ width:300px; height:300px; display: table-cell; vertical-align: middle; background-color: #ff6600; } #indemo{ width:100px; height:100px; margin:0 auto; background-color: white; }