總結解決css邊距重疊的方法

來源:互聯網
上載者:User
本篇文章主要介紹了詳解css邊距重疊的幾種解決方案,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

今天整理了一下用css防止邊距重疊的幾種方法

先假設一組dom結構


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

通常情況下,如果給子項目設定margin,就會產生這個屬性對父元素也產生了同樣的效果,然而

這其實不是我們想要的結果,我們只想對子項目設定margin,那麼現在我們應該怎麼做呢?

(1) 給父元素設定邊框


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

(2)給父元素添加padding


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

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


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

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


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

(5)給子項目設定 display: inline-block;(如果子項目是行內元素或者行內區塊層級元素則不會產生邊距重疊的問題)


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

(6)使子項目脫離文檔流這個實現的方法有很多,浮動,絕對位置等,這裡我就不做具體的解釋了。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.