【问题标题】:Are margins relative to the current element?边距是否相对于当前元素?
【发布时间】:2011-08-30 20:08:23
【问题描述】:

假设我有以下代码:

<html>
  <body>
    <header>
      <h1>
        Hello World
      </h1>
    </header>
  </body>
</html>

body{
  // make 1em equivalent to 10px when browser default is 16px 
  font-size: 62.5%;
}

header{
  font-size: 1em;
}

header h1{
  font-size: 3em;
  margin-bottom: 1em;
}

如果浏览器的默认字体大小是 16px,那么我们的 h1 就是 30px。我希望我的 h1 下方的边距是字体大小的 33%,但由于某种原因它也是 30px。就像字体大小一样。我明确指定它应该是 1em。

我知道 em 是相对于父容器的。边距是否相对于当前元素?即如果 h1 的 font-size 设置为 4em (40px),那么 1em 的边距是否也会自动变为 40px?这是预期的行为吗?我应该说margin-bottom: 0.33em

【问题讨论】:

    标签: html css font-size


    【解决方案1】:

    你的假设是正确的 1em is equal to the current font size. 所以如果我们有这个:

    <header style="font-size:10px;">
    <h1 style="font-size:2em; padding:1em;">
    Hello World
    </h1>
    <p style="padding:1em;">
    The world is a happy place
    </p>
    </header>
    

    h1 的内边距为 20 像素,p 的内边距为 10 像素。

    如果您是 ems 新手,我只记得这篇我强烈推荐的关于使用 ems 创建网页的文章:Fluid Grids

    【讨论】:

    • rem (root em) 单位也可能对您感兴趣。它是作为 CSS3 的一部分引入的。见this article
    【解决方案2】:

    我知道 em 是相对于父容器的

    没有。 em 是相对于当前字体大小的。所以在 ems 中定义字体大小是循环的。从排版上讲,您应该以 points 来定义字体大小, 而不是像素,然后获得分辨率无关性,然后在 ems 中定义边距和宽度以及缩进 &c。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-03
      • 1970-01-01
      • 2015-01-26
      • 1970-01-01
      • 1970-01-01
      • 2018-02-15
      相关资源
      最近更新 更多