在使用CSS屬性設定元素大小時,您可能會注意到兩個選項,一個是絕對單位,另一個是相對單位。絕對單位是相同的,是固定的,可以使用cm、mm、px來設定大小。另一方面,相對單位是相對於其他東西的,可以是父元素或任何其他元素。
在本教程中,我們將研究CSS中em和rem單位之間的比較。
em單位使得可以改變相對於其父元素的字體大小的元素的大小。這意味著如果父元素的大小發生變化,子元素的大小也會改變。
Let’s look at an example to understand what does the em unit do.
在這個例子中,我們將把子元素的字體大小改為35px。子元素的邊距也會改為50px。
在這裡,我們首先創建了一個父元素,然後將其大小設為17.5像素,子元素的字體大小設為1em,這意味著子元素的字體大小將是父元素的兩倍,元素的邊距將保持不變。讓我們來看一下程式碼的輸出結果。
Note − The usage of the font-size property. The font-size is relative to the father (parent) element when it is used on other properties.
<!DOCTYPE html> <html lang="en"> <head> <title>Difference between em and rem</title> <style> .father { paddding: 0px; font-size: 16px; } .son { margin: 1em; font-size: 1em; } </style> </head> <body> <div class="father"> This is the Father element <div class="son"> This is Son element </div> </div> </body> </html>
單位rem相對於元素根的字體大小,即html元素。如果沒有指定字體大小,則使用瀏覽器的預設值,不考慮父元素,只考慮根元素。
We will be keeping the font size of the child element to 50px and then setting the margin of the element to 40px. The size of the rem unit will be relative for all declarations unlike em.
In the following example, we first used the root element and then created a parent element and the child element. We then set the font size of the root element to 18px and the font-size of the parent to The 15x. and the font-size of the parent to The sizex. of the font of the child element was then set to 1.5rem which means double the size of the root element and not the parent element. Let's look at the output to see what the rem unit does.
<!DOCTYPE html> <html lang="en"> <head> <title>The difference between em and rem units</title> <style> html { font-size: 18px; } .son { font-size: 2rem; margin: 1.5rem; } .father { font-size: 13px; } </style> </head> <body> <div class="father"> This is parent <div class="son"> This is Child in rem unit system </div> </div> </body> </html>
You can see in the above output that the child element is not the double of the parent element but it is the double of the root element.
The unit em, is relative to the font-size of its nearest parent and it can lead to the compounding effect. The rem unit, is relative to the HTML root font size but it does not lead to the effing root root font size but it does not lead to the effing lead to.
##CSS中的Em與Rem單位Conclusion
以上是CSS 中的 Em 與 Rem 單位?的詳細內容。更多資訊請關注PHP中文網其他相關文章!