代碼以下:css
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>居中</title> <style type="text/css"> *{ padding: 0px; margin: 0px; } body { height: 100%; overflow: hidden; } .father{ position: absolute; height: 500px; width: 100%; background-color:#2AABD2; } .children{ position: absolute; top: 50%; left: 50%; background-color: red; width: 100px; height: 100px; margin: -50px 0 0 -50px; } </style> </head> <body> <div class="father"> <div class="children"> </div> </div> </body> </html>
效果圖以下:html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>居中</title> <style type="text/css"> *{ padding: 0px; margin: 0px; } body { height: 100%; overflow: hidden; } .father{ height: 500px; width: 100%; background-color:#2AABD2; display: flex; justify-content: center;/*實現水平居中*/ align-items:center; /*實現垂直居中*/ } .children{ background-color: red; width: 100px; height: 100px; } </style> </head> <body> <div class="father"> <div class="children"> </div> </div> </body> </html>
效果圖以下:flex
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>居中</title> <style type="text/css"> *{ padding: 0px; margin: 0px; } body { height: 100%; overflow: hidden; } .father{ position: absolute; height: 500px; width: 100%; background-color:#2AABD2; } .children { width: 300px; height: 150px; background-color: #333333; position: relative; top: 50%; left: 50%; transform: translateX(-50%) translateY(-50%); } </style> </head> <body> <div class="father"> <div class="children"> </div> </div> </body> </html>
效果圖以下:
多謝@alexxxcs1提供的另外一種方式(不曉得這樣可否@到^_^),嘛其實網上實現居中的方式確實不少,互相探討加深印象。spa