【问题标题】:Is there any way to specify line-height and margin based on the font size of the body?有没有办法根据正文的字体大小指定行高和边距?
【发布时间】:2025-12-12 20:55:02
【问题描述】:

一个直截了当的 CSS 问题。假设我们有这样的样式:

  body { 
    font-size : 16px;
  }

  p {
   font-size : 0.875em; // relative to parent, 14px
   line-height : 1em; //relative to this element, 14px
   margin-bottom : 1em; //relative to this element, 14px
  }

这意味着<p>s 的 font-size 为 14px,line-height 为 14px,margin-bottom 为 14px。

我想要的是相当于:

body : {
  font-size : 16px;
}

p { 
  font-size : 0.875em; // relative to parent, 14px;
  line-height : 1em; // relative to parent line-height, 16px;
  margin-bottom : 1em; // relative to parent margin-bottom, 16px;
}

我想要这个的原因是因为我想要一个尊重其基线的响应式字体大小。

【问题讨论】:

  • 您想要一个取决于父级的 line-height 的 line-height?
  • 使用 javascript 获取字体大小,然后进行数学运算并设置行高和边距。或者如果字体大小不是动态的,则只需对其进行硬编码
  • @Giovanni 是的,这就是我想要的。如果可能的话,还有一个边距底部。
  • @Ace,这背后的原因是要有一个响应式字体基线。使用 javascript 重新设置样式会杀死移动浏览器。
  • 您可以将line-height 设置为父容器(示例中为body)并将其从元素中删除(示例中为pjsfiddle

标签: css font-size


【解决方案1】:

从技术上讲,您可以使用rem,尽管它指的是html 元素的字体大小(因此您需要使用html 选择器,而不是body,并让body 继承来自html)。但是,浏览器支持有限。

所以最好使用em 单位,只要考虑到您的其他设置。如果p 具有font-size: 0.875em,那么要将边距设置为其父字体大小的值(计算1/0.875),您将使用相反的值:margin-bottom: 1.143em

另一方面,很自然地将body元素的字体大小视为复制文本的大小,而p元素通常是复制文本。因此,将font-sizebody(如果您设置的话)设置为所需的复制文本大小会更自然。这会让事情变得容易一些。

【讨论】:

  • caniuse.com/#search=rem 现在似乎有很好的支持。会检查的。
  • @VladNicula,缺乏对 IE 8 的支持意味着多年来,rem 对很多人都不起作用。而rem 单元实际上只是为了方便作者。
  • 好吧,如果没有 rems,我真的无法在 13px 段落上设置 16px 基线。无论如何,IE8 不是我们要开发的目标浏览器,所以我们很好:D
【解决方案2】:

如果您始终知道父元素的大小和子元素的大小,那么我可以为您提供 Sass 的解决方案。

@function em2baseline($font-size, $size: 1em, $base-size: 1em) {
    $collector: ();

    @each $s in $size {
        $collector: append($collector, ($s / $font-size * $base-size));
    }
    @return $collector;
}

$font-size 是子元素的大小,$base-size 是相对于我的$base-size 的大小列表(一个列表,因此我可以将它与边距/填充简写一起使用),$base-size 是我想让它相对于大小。

@debug em2baseline(2em);
// 0.5em

@debug em2baseline(2em, 1.5em);
// 0.75em

如果您不喜欢使用 Sass,您仍然可以自己计算:

[size you want] / [child size] * [base size]

【讨论】:

  • 谢谢,这就是我现在正在做的,计算。唯一的困难是对于 16px 基本字体大小,13px 是 0.8125ems,然后,要指定 16px 的 lineheight 形成 13px 基本大小(元素的),这意味着将 line-height 设置为 16/13,即不是一个好数字。 :)
  • 对于 line-height,Eric Meyer 关于“unitless line-height”的文章可能会让你感兴趣:meyerweb.com/eric/thoughts/2006/02/08/unitless-line-heights
最近更新 更多