css中margin-top或者margin-bottom失效

來源:互聯網
上載者:User

標籤:html   abs   容器   tin   調試   bsp   size   top   建議   

css中margin-top是設定容器的外間距了距離了,div嵌套後,margin-top或者margin-bottom失效了,在網上打到下面的方法可以解決。 

設計頁面的時候遇到一個神奇的問題,下面是html的代碼

<body>
   <div class="homeNav">
      <div class="homeCategory  ">
      </div>    
   </div>
</body>

此時我設定子容器homeCategory的樣式:


.homeCategory{
   margin-top:30px; 
}
發現margin相對的父容器搞錯了,找到body去了,成了相對於body來設定margin,此時設定了homeNav 的高度和寬度都沒效果,讓我抓狂不已,div都不聽話了,調試了半天終於找到了原因。

 

原因:

在兩個嵌套的div,如果外層div的父容器padding值為0,
那麼內層div的margin-top或者margin-bottom的值會”轉移”給外層div,也就是父容器的父容器。

 

解決辦法:

1:設定父容器的的樣式加上:overflow:hidden。
2:把對父容器的margin-top外邊距改成padding-top內邊距。
3:給父容器div加樣式, padding-top: 1px。
4:給父容器div加樣式,position: absolute。
5:把父元素變成一個 block formating context ,下面是可選的方法
a、float: left/right
b、position: absolute
c、display: inline-block/table-cell
d、overflow: hidden/auto

建議方法1。

css中margin-top或者margin-bottom失效

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.