我们知道,指定 margin-left、margin-right 为 auto 可以让一个元素左右居中。
但是如何上下居中呢?这种应用场景在哪位登录页、欢迎页非常常见。
做法一
<!DOCTYPE html> <html> <head> <style type="text/css"> html { height:100%; } body { height:100%; } body { display:flex; align-items:center; justify-content:center; } div { width:200px; height:200px; background:#ff9; } </style> </head> <body> <div></div> </body> </html>
做法二
<!DOCTYPE html> <html> <head> <style type="text/css"> html { height:100%; } body { height:100%; } div { position:absolute; top:50%; left:50%; } div { margin:-100px auto auto -100px; width:200px; height:200px; background:#ff9; } </style> </head> <body> <div></div> </body> </html>
做法三
<!DOCTYPE html> <html> <head> <style type="text/css"> div { position:absolute; top:0; bottom:0; left:0; right:0; } div { margin:auto; width:200px; height:200px; background:#ff9; } </style> </head> <body> <div></div> </body> </html>