標籤: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以及元素的寬度和高度