我將爲你們介紹3種字體單位,分別是px,em和rem。首先我先爲你們大體介紹一下,通常初學者使用字體單位px較多,1px該多大就多大是一個固定值,也就是px是一個絕對字體單位。而em和rem是相對字體單位,雖然em和rem是相對字體單位可是它們又有所不一樣,em是相對於它的父級字體大小,rem是相對於html的字體大小。如今你們確定還不是很明白,接下來我將用一段代碼向你們展現。css
1.首先爲你們介紹的是px字體單位html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> *{ padding:0; margin:0; } .box{ font-size:80px; } </style> </head> <body> <div class = "box"> <div class = "div1">你好</div> <div class = "div2">真是的</div> </div> </body> </html>
運行結果:字體
如今咱們對如今的結果進行分析:咱們如今只對box設置了字體的大小,box是div1和div2的父級,若是沒有再對div1和div2設置字體大小的話,那麼div1和div2將繼承它們父級的字體大小都是80px;htm
若是給div1和div2自己具體設置字體大小,那麼它們運行的結果不會再繼續跟隨父級。blog
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> *{ padding:0; margin:0; } .box{ font-size:80px; } .div1{ font-size:20px; } .div2{ font-size:25px; } </style> </head> <body> <div class = "box"> <div class = "div1">你好</div> <div class = "div1">真是的</div> </div> </body> </html>
運行結果:繼承
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> *{ padding:0; margin:0; } .box{ font-size:80px; } </style> </head> <body> <div class = "box"> <div class = "div3">你好</div> <div class = "div4">真是的</div> </div> </body> </html>
運行結果:utf-8
如今給div3和div4設置字體大小:rem
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> *{ padding:0; margin:0; } .box{ font-size:80px; } .div3{ font-size:2em; } .div4{ font-size:1em; } </style> </head> <body> <div class = "box"> <div class = "div3">你好</div> <div class = "div4">真是的</div> </div> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> *{ padding:0; margin:0; } html{ font-size:30px; } .box1{ font-size:60px; } </style> </head> <body> <div class = "box1"> <div class = "div5">你好</div> <div class = "div6">真是的</div> </div> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> *{ padding:0; margin:0; } html{ font-size:30px; } .box1{ font-size:60px; } .div5{ font-size:1.2rem; } .div6{ font-size:2rem; } </style> </head> <body> <div class = "box1"> <div class = "div5">你好</div> <div class = "div6">真是的</div> </div> </body> </html>
此時你好的字體大小是36px,div6的字體大小是60px;也就是說1.2rem = 1.2*30px;2em = 2*30px;而跟父級的字體大小沒有關係,若是html的字體大小變爲45px,那麼1px = 45px;也就是說rem是相對於html的字體單位。it