css------margin系列問題

一.margin與百分比問題:佈局

  1. 普通元素的百分比margin都是相對於容器寬度計算的;
  2. 絕對定位的百分比margin是相對於第一個定位祖先元素(relative/absolute/fixed)的寬度計算的;

二.margin重疊問題:spa

  1. 特性:block水平元素(不包括float和absolute元素);
  2. 不考慮writing-mode,只發生在垂直方向的(margin-top/margin-bottom);
  3. 重疊的三種狀況:(1)相鄰的兄弟元素;(2)父級和第一個/最後一個子元素;(3)空的block元素;

三.margin重疊三種狀況的具體展示:設計

  1. 父子margin重疊的條件margin-top: (1)父元素非塊狀格式化上下文              解決方法:  父元素中加入:overflow:hidden;

                                                             (2)沒有border-top設置                                     設置border-top;code

                                                             (3)沒有padding-top值                                      設置padding-top;blog

                                                             (4)父元素和第一個子元素之間沒有inline元素分隔       <div class="father">&nbsp</div>圖片

                                         margin-bottom:前四個與margin-top一致it

                                                              (5)沒有height/min-height/max-height限制         設置height元素;io

     2.空block元素margin重疊:例:
class

.father(background:#f0f3f9;overflow:hidden;)
.son(margin:1em 0;)
<div class="father">
<div class="son"></div>   <!--高度只有1em,而非2em;-->
</div>

    空block元素margin重疊的條件:     (1)元素沒有border設置容器

                                                   (2)元素沒有padding值

                                                   (3)裏面沒有inline元素

                                                   (4)沒有height或min-height

四.margin重疊的計算:(1)正正取大值(2)正負值相加(3)負負最負值

五.善用margin重疊:

     例表單列表可用

.list{
margin-top:15px;
margin-bottom:15px;
}

更具健壯性,最後一個元素移除或位置調換均不破壞原來的佈局;

六.margin:auto;問題

  1. 若本來應該填充的尺寸被width/height所強制更改;而margin:auto就是爲了填充這個變動的尺寸設計的;
  2. 若一側爲定值(margin-right:100px;),另一側爲auto(margin-left:auto;)則auto爲剩餘的空間,例width:500px,則auto爲剩餘的(500-100)px;
  3. 若兩側都爲auto,則平分剩餘空間(居中顯示);

     問題1:爲何圖片margin: 0 auto;不水平居中:

                 img{width:200px;margin:auto 0;}

 

 

              由於此時圖片是inline水平,就算沒有width,其也不會佔據整個容器;

             能夠更改成:

       img{display:block;width:200px;margin:auto 0;}

 

   問題2:容器定高,元素定高,margin:auto 0;沒法垂直居中

例      

          .father{height:200px;background:#f0f3f9;}

         .son{height:100px;width:500px;margin:auto 0;}

       可改成

 .father{height:200px;background:#f0f3f9;writing-mode:vertical-lr;}

 .son{height:100px;width:500px;margin:auto 0;}

 

也能夠改成:

 .father{height:200px;background:#f0f3f9;position:relative;}

         .son{position:absolute;top:0;left:0;bottom:0;right:0;height:100px;width:500px;margin:auto 0;}
相關文章
相關標籤/搜索