如何使用 em 而不是 px 更改 <h1> 到 <h6> 以具有与 <p> 相同的填充,同时保持它们完全相同?

How can I change <h1> through <h6> to have same padding as <p> using em instead of px while keeping them all the same?

没有代码,只有一个简单的概念,我需要帮助:

我希望填充 above/below 所有文本项 (h1-h6、p、blockquote、代码等) 相同。我希望它是 1em=16px。但是,如果我将它们全部设置为具有 1em 填充,那么像 h1 这样的较大文本项目将具有更多填充,因为它相对于 h1 的字体大小为 1em。我怎样才能让它们相对于 p 的字体大小都是 1em?

我不想使用像素作为设置宽度,因为将页面文本加倍到 1em=32px 大小不会使填充加倍,从而使其成为所需宽度的一半。我怎样才能做到这一点?

您可以使用其他单位,例如 rem, ch, ex

您将

的字体大小设置为相对于周围文本的字体大小,并且计算以 em 为单位的填充与

的填充相同。

例如:

body { font-size: 24px; }
p    { padding-top: 1em; }
h1   { font-size: 1.25em;
       padding-top: 0.8em; /* = 1 / 1.25 */
     }

视觉差距仍然会有所不同,因为您还没有说任何关于边距和行高的内容。

看看它是如何工作的(注意 0.5 = 0.625 / 1.25 是如何工作的):

<style>
  p, h1 { border: 1px solid red; }
  p { padding-top: 0.625em;
      padding-bottom: 0.625em; }
  h1 { font-size: 1.25em;
       padding-top: 0.5em;
       padding-bottom: 0.5em; }
  span { background: #DDEEFF; }
</style>

<p>This is some text which is intended as a filler to demonstrate a point.
This is some text which is intended as a filler to demonstrate a point.
This is some text which is intended as a filler to demonstrate a point.
This is some text which is intended as a filler to demonstrate a point.
This is some text which is intended as a filler to demonstrate a point.</p>

<p><span>This is some more text which is intended as a filler to demonstrate a point.
This is some more text which is intended as a filler to demonstrate a point.
This is some more text which is intended as a filler to demonstrate a point.
This is some more text which is intended as a filler to demonstrate a point.
This is some more text which is intended as a filler to demonstrate a point.</span></p>

<h1><span>Heading with the same padding as the paragraphs</span></h1>

<p>This is some other text which is intended as a filler to demonstrate a point.
This is some other text which is intended as a filler to demonstrate a point.
This is some other text which is intended as a filler to demonstrate a point.
This is some other text which is intended as a filler to demonstrate a point.
This is some other text which is intended as a filler to demonstrate a point.</p>