前端開發中,有時候會遇到設置子級div的margin屬性后,導致整個父級div整體移動,有時候卻是正常的,時而正常時而有異常。
一、問題描述:
1、css未設置margin屬性時,效果圖如下:

2、css設置 margin-top:50px 屬性時,預期效果圖如下:

3、css設置 margin-top:50px 屬性時,實際效果圖如下:

二、解決方案:
1、 給父級增加padding屬性
.父級class{ padding: 10px;// 任意值都可以 }
2、給父級增加border屬性
.父級class{ border: 1px solid transparent;// 是否有顏色自行處理 }
三、產生問題原因:
一個盒子如果沒有上補白(padding-top)和上邊框(border-top),那么這個盒子的上邊距會和其內部文檔流中的第一個子元素的上邊距重疊。、
復現代碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> html,body{ width:100%; height:100%; } .content{ width:40%; height:40%; position: relative; border: 1px solid transparent; //為了解決文中所說問題 } span { position: absolute; padding: 2px; border-style: solid; border-color: #04384e; } .row1 { border-width: 2px 0 0 2px; top: -2px; left: -2px; } .row2 { border-width: 2px 2px 0 0; top: -2px; right: -2px; } .col1 { border-width: 0 0 2px 2px; bottom: -2px; left: -2px; } .col2 { border-width: 0 2px 2px 0; bottom: -2px; right: -2px; } .title { font-size: 16px; color: #3cbeda; height: 28px; line-height: 28px; margin: 15px; padding-left: 10px; border-left: 5px solid #05c8e8; text-indent: 10px; background: rgba(5, 76, 107, 0.5); background-clip: content-box; } </style> </head> <body> <div class="content"> <span class="row1"></span> <span class="row2"></span> <span class="col2"></span> <span class="col1"></span> <div class="title"> 二級單位接入進度排名 </div> </div> </body> </html>
效果圖如下: