【问题标题】:converting pixels to ems for margins and padding将像素转换为 em 以获取边距和填充
【发布时间】:2016-04-28 23:52:02
【问题描述】:

我的边距应该是 20 像素。如何将其转换为 em?元素上的字体大小为 1.08em。 1 em = 13 像素。

我认为将 30 除以 13 可以,但似乎不行。

这是 CSS:

.test {
   margin-bottom: 30px;
   font-size: 1.23em;
}

我需要将 30px 转换为 ems。

【问题讨论】:

  • 您想要 20px 的边距,因此您将 30 除以 13?为什么是30?顺便说一句,如果您实际发布相关代码(CSS + HTML)会有所帮助。

标签: css


【解决方案1】:

设置body、html字体大小为62.5%,然后16px=1em。在这个比率下,数学变得很容易处理。

这里解释了原因。 Css 62.5% why do developers use it?

【讨论】:

    【解决方案2】:

    我有一条黄金法则,我在大多数项目中都使用它,它非常容易和简单。

    大多数浏览器的标准都是 16px,所以我将 body 和 html 定义为 100%,这样计算就很容易了。

    样本:

        //Golden Rule:  
        //100% = 16px  browsers default
        //21px ÷ 16px = 1.5em
    
    
    html,
    body {
        width: 100%;
        height: 100%;
        min-height: 100%;
        color:#565a5c;
        font: normal normal 100%/1.5em "MyriadPro", "FontAwesome";
        padding-top: 50px;
        padding-bottom: 20px;
    
    }
    

    更多示例:

    h1 {
      font-size: 2em; /* 32px ÷ 16px */
      line-height: 1.3125em; /* 42px ÷ 32px */
      margin-bottom: .5em; /* 16px ÷ 32px */
    }
    
    h2 {
      font-weight: 400;
      font-size: 1.75em; /* 28px ÷ 16px */
      line-height: 1.285714286em; /* 36px ÷ 28px */
      color: $hc;
      margin-bottom: .785714286em; /* 22px ÷ 28px */
    }
    

    30px = 1.875em

    希望对你有所帮助。

    【讨论】:

      【解决方案3】:

      我认为你在正确的轨道上。 Ems 是通过将您的 em 值乘以当前元素的继承字体大小来计算的。如果我理解正确的话,现在元素的字体大小是 14.04px,对吧? (13 像素 X 1.08)。

      使用相同的逻辑,您可以将 20 像素(您的目标边距)除以基本字体大小(13 像素),得到 1.538... 您可以四舍五入到 1.54em,您将得到 20.02 像素。

      这行得通吗?

      【讨论】:

        猜你喜欢
        • 2012-03-18
        • 2020-12-23
        • 1970-01-01
        • 1970-01-01
        • 2014-04-13
        • 1970-01-01
        • 1970-01-01
        • 2012-11-21
        • 1970-01-01
        相关资源
        最近更新 更多