內部元素居中的方式有很多種,這里就介紹一種本人認為比較方便的布局方式,主要采用flex布局,部分老舊瀏覽器可能不支持。直接上代碼吧
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .parent { width: 200px; height: 200px; border: 1px solid red; display: flex; justify-content: center; align-items: center; } .child { width: 20px; height: 20px; background-color: blue; } </style> </head> <body> <div class="parent"> <div class="child"></div> </div> </body> </html>
核心代碼就是:
display: flex;
justify-content: center;
align-items: center;
最后的效果如下: