1,position定位(推荐)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> .box01{ height: 300px; /* 这里可以改变 */ width: 300px; /* 这里可以改变 */ background-color: #6676FF; margin: auto; position: absolute; left: 0; top: 0; bottom: 0; right: 0; } </style> </head> <body> <div class="box01"></div> </body> </html>
2.flex布局 justify-content: center;(水平居中) align-items: center;(垂直居中)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> .box{ height: 100vh; width: 50%; background: #f3f300; display: flex; justify-content: center; align-items: center; } .box01{ height: 300px; /* 这里可以改变 */ width: 300px; /* 这里可以改变 */ background-color: #6676FF; } </style> </head> <body> <div class="box"> <div class="box01"></div> </div> </body> </html>
3.display:table-cell 表格
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> .box{ height: 100vh; width: 50%; background: #f3f300; display: table-cell; vertical-align: middle; } .box01{ height: 300px; /* 这里可以改变 */ width: 300px; /* 这里可以改变 */ background-color: #6676FF; margin: 0 auto; } </style> </head> <body> <div class="box"> <div class="box01"></div> </div> </body> </html>
4.position定位 + transform过渡
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> .box{ height: 100vh; width: 50%; background: #f3f300; position: relative; } .box01{ height: 300px; /* 这里可以改变 */ width: 300px; /* 这里可以改变 */ background-color: #6676FF; position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); } </style> </head> <body> <div class="box"> <div class="box01"></div> </div> </body> </html>