1. 程式人生 > >深入理解css模型

深入理解css模型

  • 基本概念:標準模型和IE模型
  • css如何設定這兩種模型
  • JS如何設定獲取盒模型對應的寬和高
  • 例項題(根據盒模型解釋邊距重疊)
  • BFC(邊距重疊解決方案)

基本概念

1.盒模的組成:
content,padding,border,margin
2.兩種盒模型:一個是標準盒模型,一個是IE的怪異模型。
標準模型
這裡寫圖片描述
IE的怪異模型
這裡寫圖片描述

盒模型的寬和高:內容(content)的寬高
IE模型的寬和高:內容(content)+填充(padding)+邊框(border)的總寬高

css如何設定兩種模型

這裡用到了css3的屬性box-sizing
/* 標準模型 */ box-sizing:content-box; /*IE模型*/ box-sizing:border-box;

JS獲取寬高

通過JS獲取盒模型對應的寬盒高,有以下幾種方法:
1、 dom.style.width/height
這種方式只能取到dom元素內聯樣式所設定的寬高,也就是說如果該節點的樣式是在style標籤中或外聯的CSS檔案中設定的話,通過這種方法是獲取不到dom的寬高的。
2、dom.currentStyle.width/height
 這種方式獲取的是在頁面渲染完成後的結果,就是說不管是哪種方式設定的樣式,都能獲取到。但這種方式只有IE瀏覽器支援。
3、dom.getBoundingClientRect().width/height
這種方式是根據元素在視窗中的絕對位置來獲取寬高的
4、window.getComputedStyle(dom).width/height
這種方式的原理和2是一樣的,這個可以相容更多的瀏覽器,通用性好一些。
5、dom.offsetWidth/offsetHeight
這個就沒什麼好說的了,最常用的,是相容最好的。

邊距重疊

什麼是邊距重疊
如下圖,父元素沒有設定margin-top,而子元素設定了margin-top: 20px;可以看出,父元素也一起有了邊距。
這裡寫圖片描述
上圖的程式碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        *{
            margin:0;
            padding:0;
        }
.demo{ height:100px; background: #eee; } .parent{ height:200px; background: #88f; } .child{ height:100px; margin-top:20px; background: #0ff; width:200px; }
</style> </head> <body> <section class="demo"> <h2>此部分是能更容易看出讓下面的塊的margin-top。</h2> </section> <section class = "parent"> <article class="child"> <h2>子元素</h2> margin-top:20px; </article> <h2>父元素</h2> 沒有設定margin-top </section> </body> </html>

邊距重疊解決方案(BFC)

首先要明確BFC是什麼意思,其全英文拼寫為 Block Formatting Context 直譯為“塊級格式化上下文”
BFC的原理
內部的box會在垂直方向,一個接一個的放置
每個元素的margin box的左邊,與包含塊border box的左邊相接觸(對於從做往右的格式化,否則相反)
box垂直方向的距離由margin決定,屬於同一個bfc的兩個相鄰box的margin會發生重疊
bfc的區域不會與浮動區域的box重疊
bfc是一個頁面上的獨立的容器,外面的元素不會影響bfc裡的元素,反過來,裡面的也不會影響外面的
計算bfc高度的時候,浮動元素也會參與計算
怎麼取建立bfc
float屬性不為none(脫離文件流)
position為absolute或fixed
display為inline-block,table-cell,table-caption,flex,inine-flex
overflow不為visible
根元素
應用場景
自適應兩欄佈局
清除內部浮動
防止垂直margin重疊
看一個垂直margin重疊例子

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        *{
            margin:0;
            padding:0;
        }
        .top{
            background: #0ff;
            height:100px;
            margin-bottom:30px;
        }
        .bottom{
            height:100px;
            margin-top:50px;
            background: #ddd;
        }
    </style>
</head>
<body>
    <section class="top">
        <h1></h1>
        margin-bottom:30px;
    </section>
    <section class="bottom">
        <h1></h1>
        margin-top:50px;
    </section>
</body>
</html>

效果圖
這裡寫圖片描述
用bfc可以解決垂直margin重疊的問題

關鍵程式碼

<section class="top">
        <h1></h1>
        margin-bottom:30px;
    </section>
    <!-- 給下面這個塊新增一個父元素,在父元素上建立bfc -->
    <div style="overflow:hidden">
        <section class="bottom">
            <h1></h1>
            margin-top:50px;
        </section>
    </div>

效果圖
這裡寫圖片描述
關於bfc的應用的案例這裡就不在一一舉出了,大家去網上找一些其他的文章看一下。