css居中
阿新 • • 發佈:2020-08-26
一、定位居中
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style type="text/css"> .out { width: 300px; height: 300px; background: red; position: relative; } .in { width: 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 { width: 300px; height: 300px; background: red; display: flex; flex-direction: row; /*定義主軸方向,row為預設值*/ justify-content: center; /*主軸對齊方式*/ align-items: center; /*交叉軸對齊方式*/ } .in { width: 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 { width: 300px; height: 300px; background: red; text-align: center; } .in { width: 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>