CSS 中相對長度 rem 和 em 如何區別

來源:互聯網
上載者:User
rem vs em

做為相對長度單位的倆個活寶, 都是以倍數關係定長度,只是參照物不一樣,這裡就案例分析兩者的區別:
1,em 的參照倍數對象為其自身字型大小,font-size;如果沒有向上繼承;
2,rem的參照倍數對象為根項目

案例代碼:

<html style="font-size:14px"><div style="font-size:14px;background:#bbb;border:1px solid #f00;margin-bottom:5px;">        this is a 14px div        <p style="font-size:1em;background:#ccc;">            this is a 1em p in 14px div        </p>    </div>    <div style="font-size:10px;background:#b71119;border:1px solid #006f00;color:#fff;margin-bottom:5px">        this is a 10px  div        <p style="font-size:2em;background:#b0b000">            this is a 2em p in 10px div            <span style="font-size:1em;color:#b71119">               span: this is a 1em span in 2emp of 10px div;            </span>        </p>    </div>    <div style="font-size:1rem;background:#ee7324;padding-bottom: 1px;">        this is 1rem div        <p style="font-size:2rem;background: #eee">            this is a 2rem p in 1rem div            <span style="font-size:.5rem;color:green">span: this is a 0.5rem span in 2rem p of 1rem div</span>        </p>    </div>

使用:
如果是跟父元素成倍數關係縮放大小,可選擇em為單位;
rem常用在移動端開發,是非常不錯的選擇,可解決不同螢幕下的顯示不適應情況,後面會介紹如何使用100%布局和rem 來開發移動端業務。

相關文章

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.