Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

How does rem differ from em in CSS?

In website source, I have sometimes seen developers use the rem unit. Is it similar to em? I tried it to see what it actually does, but what is it relative to?

Demo

HTML

<div>Hello <p>World</p></div>

CSS

div {
    font-size: 1.4rem;
}

div p {
    font-size: 1.4rem;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

EMs are relative to the element's parent's font size

REMs are relative to a base font-size of your browser

You would use REM for accessibility because the (REM) font sizes of your website will adjust according to the browser's font size. For example, if you had a p tag with a font size of 2 rem and your browser's font size is 16, its computed font size would be 32 pixels or 2 times the browser's base font size.

// logs the font size of element clicked
document.addEventListener("click", function(event) {
  if (event.target.tagName !== "" && event.target.id !== "") {
    console.log("font size for " + event.target.innerText + " is " + window.getComputedStyle(document.querySelector("#" + event.target.id), null).getPropertyValue("font-size"));
  } else {}
});
/* style the first paragraph*/

#foo {
  font-size: 2rem;
}


/* style the parent div of the second paragraph*/

div {
  font-size: 32px;
}


/* style the second paragraph which is the child of the div*/

#bar {
  font-size: 2em;
}
<!-- this paragraph's font size is two times your browser's base font size(its computed style is 32px if your browser font size is 16) -->
<p id="foo">foo</p>
<div>
  <!-- this paragraph's font size is two times the parent element's(the div) font size(64px) -->
  <p id="bar">bar</p>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...