css邊距重疊的解決方案

**css

css防止邊距重疊的方法

** dom

今天整理了一下用css防止邊距重疊的幾種方法
先假設一組dom結構code

<div class="parent">
    <div class="child">
    </div>
</div>

一般狀況下,若是給子元素設置margin,就會產生這個屬性對父元素也產生了一樣的效果,然而
這其實不是咱們想要的結果,咱們只想對子元素設置margin,那麼如今咱們應該怎麼作呢?
(1) 給父元素設置邊框文檔

.parent { 
    width: 300px;       
    height: 300px;
    border: 1px solid #ccc;
}
.child {
    width: 200px;
    height: 200px;
    margin: 20px;
}

(2)給父元素添加paddingclass

.parent {
    padding: 1px;
    width: 300px;
    height: 300px;
}
.child {
    width: 200px;
    height: 200px;
    margin: 20px;
}

(3)在子元素上方加一個有寬高的兄弟元素,記住是有寬高的。方法

<div class="parent">
     <div style="width: 20px;height: 20px;margin-top: "></div>
     <div class="child">
     </div>
</div>

(4)給父元素設置 overflow: hidden; 屬性margin

.parent {
    overflow: hidden;
    width: 300px;
    height: 300px;
}
.child {
    width: 200px;
    height: 200px;
    margin: 20px;
}

(5)給子元素設置 display: inline-block;(若是子元素是行內元素或者行內塊級元素則不會產生邊距重疊的問題)top

.parent {
    width: 300px;
    height: 300px;
} 
.child {
    width: 200px;
    height: 200px;
    margin: 20px; 
    display: inline-block;
}

(6)使子元素脫離文檔流這個實現的方法有不少,浮動,絕對定位等,這裏我就不作具體的解釋了。
但願能夠能幫助到須要的人,若是你以爲這個文章幫到你了,就麻煩動動小手點個贊吧!嘿嘿di

相關文章
相關標籤/搜索