像素和相對長度css
前面的html博文,咱們提到過用屬性width、height來設置圖片的尺寸,它們的單元都是」px(像素)」。
長度單位總結一下,目前比較經常使用到px(像素)、em、% 百分比,要注意其實這三種單位都是相對單位。
一、像素
像素爲何是相對單位呢?由於像素指的是顯示器上的小點(CSS規範中假設「90像素=1英寸」)。實際狀況是瀏覽器會使用顯示器的實際像素值有關,在目前大多數的設計者都傾向於使用像素(px)做爲單位。html
二、em瀏覽器
就是本元素給定字體的 font-size 值,若是元素的 font-size 爲 14px ,那麼 1em = 14px;若是 font-size 爲 18px,那麼 1em = 18px。less
p { font-size:12px; text-indent:2em; }
上面代碼就是能夠實現段落首行縮進 24px(也就是兩個字體大小的距離)。學習
三、百分比字體
設置行高(行間距)爲字體的130%(12 * 1.3 = 15.6px)。網站
p{ font-size:12px; line-height:130% }
px的特色:
1. IE沒法調整那些使用px做爲單位的字體大小;
2. 國外的大部分網站可以調整的緣由在於其使用了em或rem做爲字體單位;設計
3. Firefox可以調整px和em,rem,可是96%以上的中國網民使用IE瀏覽器(或內核)。code
em的特色:
1. em的值並非固定的;htm
2. em會繼承父級元素的字體大小。
rem的特色:
rem是CSS3新增的一個相對單位(root em,根em),這個單位引發了普遍關注。這個單位與em區別在於使用rem爲元素設定字體大小時,仍然是相對大小,但相對的只是HTML根元素。
看段html和css代碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="index.css"> <title></title> </head> <body> <h1>像素和相對長度</h1> <div>青春</div> <div>財富</div> <div>愛情</div> </body> </html>
body { margin: 0; } div { width: 100px; height: 100px; line-height: 100px; text-align: center; margin-left: 20px; margin-bottom: 20px; font-size: 24px; font-weight: bold; background-color: lightgreen; color: RGB(0, 0, 0); } div + div { background-color: lightpink; margin-left: 70px; } div + div + div { background-color: brown; color: #FFFFFF; margin-left: 120px; }
更多學習內容,就在碼芽網http://www.mayacoder.com/lesson/index