display: inline/inline-block
将父元素(容器)设定 text-align: center; 即可左右置中。
display: block
将元素本身的 margin-left 和 margin-right 设定为auto; 即可左右置中。
方法一:Position: Absolute 对齐元素本身
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>上下左右居中对齐</title> <style type="text/css"> #box { width: 100px; height: 100px; border: 2px solid #0000FF; } #box { position: absolute; top: 50%; left: 50%; transform: translateX(-50%) translateY(-50%);
/* 或者这样写 */ right: 50%; bottom: 50%; transform: translateX(50%) translateY(50%); } </style> </head> <body> <div id="box"></div> </body> </html>
方法二:Flexbox 对齐元素内容
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>上下左右居中对齐</title> <style type="text/css"> #box { width: 100px; height: 100px; border: 2px solid #0000FF; } body { min-height: 100vh; display: flex; justify-content: center; align-items: center; } </style> </head> <body> <div id="box"></div> </body> </html>
方法三:Display : Table 对齐元素内容
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>上下左右居中对齐</title> <style type="text/css"> #box { width: 100px; height: 100px; border: 2px solid #0000FF; display: inline-block; } body { display: table; width: 100%; min-height: 100vh; margin: 0; } .cell { display: table-cell; vertical-align: middle; text-align: center; } </style> </head> <body> <div class="cell"> <div id="box"></div> </div> </body> </html>