乐闻世界logo
搜索文章和话题

What is the difference between em and rem units in CSS?

1个答案

1

In CSS, both em and rem are relative units used to set properties such as font size, padding, and margin for elements. The primary distinction is that em is relative to the parent element's font size, whereas rem is relative to the root element's font size.

em Unit

The em unit is defined relative to the parent element's font size. For example, if a parent element has a font size of 16px, then 1em equals 16px. If a child element inside this parent has its font-size set to 2em, the child's font size will be 32px (16px * 2).

  • Example: Consider an HTML structure with a paragraph <p> inside a div container. The div has a font size set to 20px, and the paragraph's font size is set to 1.5em. The actual font size of the paragraph will be 30px (20px * 1.5).
html
<div style="font-size: 20px;"> <p style="font-size: 1.5em;">This is a paragraph.</p> </div>

rem Unit

The rem unit is defined relative to the root element (i.e., the HTML element)'s font size. Regardless of the document hierarchy, 1rem always has the same value, determined by the root element's font size.

  • Example: If the HTML element's font size is set to 16px, then 1rem equals 16px at any position in the document. No matter how deeply nested, rem is based on the root element's font size.
html
<html style="font-size: 16px;"> <body> <div style="font-size: 20px;"> <p style="font-size: 1.5rem;">This is a paragraph.</p> </div> </body> </html>

In this example, regardless of the div's font size, the paragraph's font size remains 24px (16px * 1.5) because it is calculated based on the HTML element's font size.

Usage Scenarios

  • em: Use em when you want element styles (such as font size and spacing) to be closely related to the parent element's font size.
  • rem: Use rem when you need a consistent layout without being affected by the parent element's font size. It ensures uniform font size across the entire page, especially valuable in responsive design.

In summary, understanding and choosing between em and rem depends on whether you want the styles to align with the parent element's font size or the root element's font size.

2024年7月26日 13:46 回复

你的答案