1.使用CSS3 的伸缩盒布局
<!doctype html> <html> <head> <meta charset="utf-8"> <style> #container { height: 400px; width: 100%; background-color: gray; display:-webkit-flex; display: flex; flex-direction: row; -webkit-flex-direction: row; -webkit-justify-content: center; justify-content: center; -webkit-align-items: center; align-items: center; } #container > div{ height: 200px; width: 200px; background-color: red; } </style> </head> <body> <div id="container"> <div></div> </div> </body> </html>
2.position:absolute 和 margin 联合使用
<!doctype html> <html> <head> <meta charset="utf-8"> <style> #container { height: 400px; width: 100%; background-color: gray; position: relative; } #container > div{ height: 200px; width: 200px; background-color: red; position: absolute; top: 50%; left: 50%; margin: -100px 0 0 -100px; } </style> </head> <body> <div id="container"> <div></div> </div> </body> </html>
3.position:absolute 和 margin: auto联合使用
<!doctype html> <html> <head> <meta charset="utf-8"> <style> #container { height: 400px; width: 100%; background-color: gray; position: relative; } #container > div{ height: 200px; width: 200px; background-color: red; position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; } </style> </head> <body> <div id="container"> <div></div> </div> </body> </html>
时间: 2024-10-10 17:38:06