如何使不同字体大小的按钮高度相同

How to make button heights the same with different font sizes

我无法使不同字体大小的按钮高度相同。我必须使用 em 作为响应式设计的高度和宽度。

这里是例子jsfiddle

CSS:

body{
  font-size:16px;
}
.btn{
  height:4em;
  font-size:1em;
}
.btn2{
  height:4em;
  font-size:1.50em;
}

HTML:

<button class="btn">First Button is 64px as expected</button>
<br><br>
<button class="btn2">Why this is not same height with first one?</button>

<p>
  How to make same height buttons with differnet font sizes ? 
</p>

ems 与字体大小相关,因此当您更改 btn2 的字体大小时,您正在更改 height: 4em 的计算结果。 rems 将为您解决这个问题如果您能够使用它们:

body{
  font-size:16px;
}
.btn{
  height: 4rem;
  font-size:1em;
}
.btn2{
  font-size:1.50em;
  height: 4rem;
}
<button class="btn">First Button is 64px as expected</button>
<br><br>
<button class="btn2">Why this is not same height with first one?</button>

<p>
  How to make same height buttons with differnet font sizes ? 
</p>

两个 <button> 元素大小不同的原因是因为您根据相对 em 大小单位定义 height,这是根据当前大小确定的font-size,并且两个 <button> 元素具有不同的 font-size.

虽然您说“必须使用 em 来...响应式大小调整,但您可以改为使用 rem 单位,即 'root-em',一个 rem 将始终是相同的大小,而不管任何后代元素的更改 font-size

例如:

let button1 = document.querySelector('button.btn'),
  button2 = document.querySelector('button.btn2');

console.log(button1.clientHeight, button2.clientHeight);
// 60 60 (in my browser, yours will vary, but both
// buttons should show the same size).
body {
  font-size: 16px;
  box-sizing: border-box;
}

.btn {
  height: 4rem;
  line-height: 4rem;
  font-size: 1em;
}

.btn2 {
  height: 4rem;
  line-height: 4rem;
  font-size: 1.50em;
}
<button class="btn">First Button is 32px as expected</button>
<br />
<br />
<button class="btn2">Why this is not same height with first one?</button>

<p>
  How to make same height buttons with differnet font sizes ?
</p>

您正在为字体设置 ems,为高度设置 ems。 'em' 相当于当前字体大小。它由您的初始 body CSS 设置为 16px,因此 1em = 16px,其中 * 4 为 btn 的高度为 64px。当您更改 btn2 中的字体大小时,您正在调整该对象作为一个整体的 em 值,因此您的 4 em 高度现在为 1.5 * 16px * 4 = 96px。

除非您能够将按钮的 em 值与字体大小 em 分开设置,否则我认为如果不手动将 4em 减小到更小的值,您就不会成功,因此数学会在 btn2 上计算出来。如果您希望保持一致的 4em,那么我建议以某种方式嵌套元素,以便您可以在单独的元素上设置值。