发布于 2026-01-06 1 阅读
0

还在为用计算器把“px”转换成“em”而烦恼吗?SASS 可以帮你解决这个问题。

还在为用计算器把“px”转换成“em”而烦恼吗?SASS 可以帮你解决这个问题。

大家好,我是Aya Bouchiha,今天我决定和大家分享使用计算器将“px”转换为“rem”或“em”的解决方案,因为使用计算器会让你分心,难以专注于工作,还会浪费大量时间,尤其是在项目很大或者电脑运行缓慢的情况下。

布奇哈绫

px是什么?

  • px:是绝对测量单位。

它们是什么?

  • em:是相对于其父元素字体大小的相对单位,用于测量,它等于 16px。

px、em 和 rem 的区别

将 px 转换为 em

默认情况下:
1em = 16px
pxValue = emValue * 16
emValue = pxValue / 16

我应该使用计算器将 px 转换为 em 吗?

  • 如果你熟悉 SCSS,那么答案是:不,不,不!那么该怎么做呢?

创建一个将 px 转换为 em 的函数

index.scss

@function to-em($val-px){
    @return ($val-px / 16) + em;
}
Enter fullscreen mode Exit fullscreen mode

测试我们的功能

index.scss

// index.scss

// px => em
@function to-em($val-px){
    @return ($val-px / 16) + em;
}

h1 {
    font-size:to-em(24);
}
div {
    height: to-em(200);
    width: to-em(400);
}
Enter fullscreen mode Exit fullscreen mode

结果

index.css

h1 {
  font-size: 1.5em;
}

div {
  height: 12.5em;
  width: 25em;
}
Enter fullscreen mode Exit fullscreen mode

祝你今天过得愉快!

文章来源:https://dev.to/ayabouchiha/are-you-bored-of-converting-px-to-em-using-a-calculator-sass-will-solve-the-problem-2cp6