CSS單位,em,rem以及元素的寬度和高度

來源:互聯網
上載者:User

標籤:size   自身   offset   尋找   root   code   log   大小   setw   

一、em和rem

說到調適型配置,就不得不提到rem這個單位。

簡單的說

  • em: 就是字型大小,根據元素自身的字型大小來定,如果自身沒有定義字型大小,則繼承父元素的字型大小,即1em = 1 font-size;
  • rem: 和em差不多,可以看成是root-em,是根據根項目的字型大小來定義的,即html設定的字型大小來定義,預設html的字型大小是16px;

用一個demo來說明最好:

<style>html{    font-size: 50px;}    #wrapper{        font-size: 40px;        background-color:red;        width:2em;        height: 2em;    }    #outter{        font-size: 20px;        background-color: yellow;        width: 2em;        height: 2em;    }    #inner{        font-size: 10px;        background: blue;        width: 2em;        height: 2em;    }    #wrapper-1{        font-size: 40px;        background-color:red;        width:2rem;        height: 2rem;    }    #outter-1{        font-size: 20px;        background-color: yellow;        width: 2rem;        height: 2rem;    }    #inner-1{        font-size: 10px;        background: blue;        width: 2rem;        height: 2rem;    }</style><body>    <div id = ‘wrapper‘>        <div id = ‘outter‘>            <div id = ‘inner‘>0</div>        </div>    </div>    <div id = ‘wrapper-1‘>        <div id = ‘outter-1‘>            <div id = ‘inner-1‘>1</div>        </div>    </div></body>

結果,上為用em,為rem

可以看到用em的大小根據自身元素字型大小的變化而變化,而用rem則不會,一直以根font-size為標準。

 

二、寬度和高度

單我想擷取上面元素的寬度時,我習慣的用了:

document.getElementById(‘wrapper‘).style.width // 結果是“”

找了一下資料,發現這是尋找設定了的css元素屬性時使用的,而一般應該用以下方法:

1.clientWidth和clientHeight

var width = el.clientWidth;var height = el.clienHeight;

說明:padding和scroll變動,才有變化

2.scrollWidth 和box.scrollHeight

var width = el.scrollWidth;var height = el.scrollHeight;

說明,1)border變化,不同瀏覽器有不同變化2)padding變化,有變化3)margin變化,無變化

3.offsetWidth和offsetHeight

var width = el.offsetWidth;var height = el.offsetHeight;

說明,padding和border有變動,才有變化

CSS單位,em,rem以及元素的寬度和高度

聯繫我們

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