一、定位居中
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> .out { 300px; height: 300px; background: red; position: relative; } .in { 100px; height: 100px; background: green; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } </style> </head> <body> <div class="out"> <div class="in"></div> </div> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> .out { 300px; height: 300px; background: red; position: relative; } .in { 100px; height: 100px; background: green; position: absolute; margin: auto; top: 0; right: 0; bottom: 0; left: 0; } </style> </head> <body> <div class="out"> <div class="in"></div> </div> </body> </html>
二、弹性布局
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> .out { 300px; height: 300px; background: red; display: flex; flex-direction: row; /*定义主轴方向,row为默认值*/ justify-content: center; /*主轴对齐方式*/ align-items: center; /*交叉轴对齐方式*/ } .in { 100px; height: 100px; background: green; } </style> </head> <body> <div class="out"> <div class="in"></div> </div> </body> </html>
三、vertical-align
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> .out { 300px; height: 300px; background: red; text-align: center; } .in { 100px; height: 100px; background: green; display: inline-block; vertical-align: middle; } .verticalaligndiv { height: 100%; display: inline-block; vertical-align: middle; } </style> </head> <body> <div class="out"> <!--两个div之间不能有换行或空格,否则居中会有误差--> <div class="verticalaligndiv"></div><div class="in"></div> </div> </body> </html>