absolute定位有一個很常用的用途,就是當希望子元素在父元素的正中央時,可以這樣操作:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .box{ width: 500px; height: 500px; background: blue; position: absolute; top: 100px; left: 100px; } .son{ width: 100px; height: 100px; background: black; position: absolute; left: 0; /* 注意不要漏了上下左右為0,否則不會成功 */ right: 0; top: 0; bottom: 0; margin: auto; } </style> </head> <body> <div class="box"> <div class="son"></div> </div> </body> </html>