CSS盒模型

css和模型的基本概念:css

  包括:外邊距(marign)、邊框(border)、內容(content) 、內邊距(padding)。html

  css盒模型還區分:標準盒模型 和 IE盒模型瀏覽器

標準盒模型和IE模型區別:dom

  IE盒模型和標準模型的區別是:寬高的計算方式不一樣flex

  IE盒模型中,寬度爲 左右邊框的寬度 + 左右內邊距的寬度+content;高度爲:上下邊框高度 + 上下內邊距高度 + content 。以下圖:spa

  

  標準盒模中,寬度爲content的寬度;高度爲content的高度。 以下圖:code

 

css如何設置這兩種模型orm

  標準模型設置:box-sizing:content-box  (瀏覽器默認設置的是標準盒模型)htm

   IE模型設置:box-sizing: border-boxblog

js如何設置獲取盒模型對應的寬高

  1.dom.style.width/height (只適用內聯樣式的寬高,若是元素沒有設置內聯寬高則取不到值)

  2.dom.currentStyle.width/height (獲取渲染後的寬高,但只適用於ie瀏覽器)

  3.window.getcomputedCurrentStyle(dom).width/height (獲取渲染後的寬高,兼容性比較好)

  4. dom.getBoundingClientRect().width/height (計算元素的絕對位置,相對於視窗的左上角,能夠獲取到 width height top left right bottom)

nargin 縱向重疊問題

  * 相鄰元素的 margin-top 和 margin-bottom 會發生重疊

  eg: 以下代碼 aa 和 bb 之間的距離是多少

<style>
    div{
        height: 20px;
        margin-top: 10px;
        margin-bottom: 15px;
    }
</style>
<div>aa</div>
<div>bb</div>

 

  答案是: 15px

BFC(塊級格式化上下文  Block format context)

  BFC的基本概念:塊級格式化上下文

  BFC的原理(或者說BFC的渲染規則):

    1. 在同一個BFC中,兩個相鄰的元素垂直方向的外邊距會重疊

    2. BFC的區域不會與浮動元素重疊

    3.BFC是一個獨立的容器,外面的元素不會影響子元素,反之BFC裏面的子元素也不會影響外面的元素

    4. 計算BFC的高度時,浮動元素也參與計算

  如何建立BFC:

    1. float 值不爲none

    2. position 的值爲:absolute 後者 fixed

    3. distable 的值爲: table 、table-cell 、table-caption 、flex 、inline-block

    4.塊級元素設置overflow,而且值不爲visible.

  BFC用途:

    1.清除浮動

      浮動元素的父級的高度不能被撐開,能夠爲父元素設置:overflow:hidden 。

    2.解決外邊距重疊問題

      例子:

style>
   html,body{
       margin:0;
       height:100%;
   }
  div{
      width: 100px;
      height: 100px;
      background:red;
  }
    .top{
        margin-bottom:100px;
    }
   .bottom{
       margin-top:50px;
   }
</style>
<div class="top">1</div>
<div class="bottom">2</div>

運行能夠看到這兩個div中間的距離是100px,而不是150px。這就是由於邊距重疊了。

解決方案就是爲其中一個元素外面加一層元素,併爲這個元素設置:overflow:hidden 。使其造成BFC。BFC內部是一個獨立的容器,不會與外部相互影響,能夠防止margin重疊。

<style>
   html,body{
       margin:0;
       height:100%;
   }
   .top,.bottom{
      width: 100px;
      height: 100px;
      background:red;
  }
   .top{
        margin-bottom:100px;
   }
   .bottom{
       margin-top:50px;
   }
</style>
<div style="overflow:hidden;">
    <div class="top">1</div>
</div>
<div class="bottom">2</div>
相關文章
相關標籤/搜索