如何使用em而不是px将<h1>到<h6>更改为与<p>相同的填充,同时保持它们不变?

时间:2019-10-05 02:24:20

标签: html css margin padding

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

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

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

相对于周围文本的字体大小设置

的字体大小,并计算ems中的填充与

的填充相同。

例如:

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>