學習CSS布局 - box-sizing

來源:互聯網
上載者:User

標籤:屬性   idt   首碼   ref   var   nbsp   學習   imp   set   

box-sizing

人們慢慢的意識到傳統的盒子模型不直接,所以他們新增了一個叫做 box-sizing 的CSS屬性。

當你設定一個元素為 box-sizing: border-box; 時,此元素的內邊距和邊框不再會增加它的寬度。

這裡有一個與前一頁相同的例子,唯一的區別是兩個元素都設定了 box-sizing: border-box; 

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>box-sizing</title>    <style>        /** {            box-sizing: border-box;            -webkit-box-sizing: border-box;            -moz-box-sizing: border-box;            -ms-box-sizing: border-box;            -o-box-sizing: border-box;        }*/        .simple {            width: 400px;            height: 200px;            border: 1px solid red;            margin: 20px auto;            box-sizing: border-box;            -webkit-box-sizing: border-box;            -moz-box-sizing: border-box;            -ms-box-sizing: border-box;            -o-box-sizing: border-box;        }        .fancy {            width: 400px;            height: 200px;            border: 1px solid red;            margin: 20px auto;            padding: 50px;            box-sizing: border-box;            -webkit-box-sizing: border-box;            -moz-box-sizing: border-box;            -ms-box-sizing: border-box;            -o-box-sizing: border-box;        }    </style></head><body>    <div id="simple" class="simple">我是simple</div>    <div id="fancy" class="fancy">我和simple一樣大了</div>    <script>        var oDiv1 = document.querySelector(‘#simple‘);        console.log(oDiv1.offsetWidth, oDiv1.offsetHeight);        var oDiv2 = document.querySelector(‘#fancy‘);        console.log(oDiv2.offsetWidth, oDiv2.offsetHeight);    </script></body></html>

結果:

 

既然沒有比這更好的方法,一些CSS開發人員想要頁面上所有的元素都有如此表現。

所以開發人員們把以下CSS代碼放在他們頁面上:

* {            box-sizing: border-box;            -webkit-box-sizing: border-box;            -moz-box-sizing: border-box;            -ms-box-sizing: border-box;            -o-box-sizing: border-box;        }

這樣可以確保所有的元素都會用這種更直觀的方式排版。

不過 box-sizing 是個很新的屬性,目前你還應該像我上面例子中那樣使用 -webkit-和 -moz- 首碼。

這可以啟用特定瀏覽器實驗中的特性。同時記住它是支援IE8+的。

 

原文地址:http://zh.learnlayout.com/box-sizing.html

學習CSS布局 - box-sizing

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.