盒模型水平居中
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> * { margin: 0; padding: 0; } #wrap { 500px; height: 500px; background: grey; position: relative; } #box{ position: absolute; top: 0; left: 0; bottom: 0; right: 0; margin: auto; 200px; height: 200px; background: deeppink; } </style> </head> <body> <div id="wrap"> <div id="box"></div> </div> </body> <script type="text/javascript"> window.onload = function () { var box = document.getElementById('box'); } </script> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> * { margin: 0; padding: 0; } #wrap { 500px; height: 500px; background: grey; position: relative; } #box{ position: absolute; top: 50%; left: 50%; margin-top: -100px; margin-left: -100px; 200px; height: 200px; background: deeppink; } </style> </head> <body> <div id="wrap"> <div id="box"></div> </div> </body> <script type="text/javascript"> window.onload = function () { var box = document.getElementById('box'); } </script> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> * { margin: 0; padding: 0; } #wrap { 500px; height: 500px; background: grey; position: relative; } #box{ position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); 200px; height: 200px; background: deeppink; } </style> </head> <body> <div id="wrap"> <div id="box"></div> </div> </body> <script type="text/javascript"> window.onload = function () { var box = document.getElementById('box'); } </script> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> * { margin: 0; padding: 0; } #wrap { 500px; height: 500px; background: grey; display: flex; justify-content: center; align-items: center; } #box{ 200px; height: 200px; background: deeppink; } </style> </head> <body> <div id="wrap"> <div id="box"></div> </div> </body> <script type="text/javascript"> window.onload = function () { var box = document.getElementById('box'); } </script> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> * { margin: 0; padding: 0; } #wrap { 500px; height: 500px; background: grey; display: -webkit-box; -webkit-box-pack: center; -webkit-box-align: center; } #box{ 200px; height: 200px; background: deeppink; } </style> </head> <body> <div id="wrap"> <div id="box"></div> </div> </body> <script type="text/javascript"> window.onload = function () { var box = document.getElementById('box'); } </script> </html>
图片水平居中:
//利用伪元素
<style> * { margin: 0; padding: 0; } html,body{ height: 100%; } body{ text-align: center; } body::after{ content: ""; display: inline-block; height: 100%; vertical-align: middle; } img{ vertical-align: middle; } </style> </head> <body> <img src="https://placehold.it/200x200"> </body>