DEV Community

HandsomeTan
HandsomeTan

Posted on

Css em, rem units compatible with mobile devices

Assuming the width of mobile design drafts is 750px, we can divide the width into 20 equal parts(a custom number for setting the font size attribute of HTML elements conveniently), and then set 1rem = 750px/20 = 37.5px through @media screen and (max-width: 768px).

example of setting css rem unit in different size of mobile devices

@media screen and (max-width: 750px) {
  font-size: 37.5px;
}
@media screen and (max-width: 375px) {
  font-size: 18.75px;
}
// and so on


//  px to rem
.test {
 width: 10rem; (corresponding to 375px on 750px device and 187.5px on 375px device)
}
Enter fullscreen mode Exit fullscreen mode

It is suitable to use the rem unit for mobile compatiability such as elements' font-size.

The em unit is relative to the font sieze of element itself, and is usually used for setting padding, margin, border-width, and so forth.

Top comments (0)