margin-top/top 百分比的是相對誰
阿新 • • 發佈:2019-01-04
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin: 0; padding: 0; } .wrap{ width: 600px; height: 800px; background: gray; position: relative; margin: 300px auto; } .box{ width: 300px; height: 400px; background: #000; position: absolute; top: 50%; margin-top: -50%; } </style> </head> <body> <div class="wrap"> <div class="box"></div> </div> </body> </html>
效果和沒設定margin-top top前一樣,不同之處在於現在的.box脫離了父級
如果我們嘗試下修改父級.wrap的寬度為800px,會發現以下情況:
黑色塊往上移動了100px 剛好等於800/2-300,由此可知,margin-top是相對position:releative;父級的寬度而言的,