为什么按钮中的文本总是垂直居中?

Why is the text in a button always centered vertically?

我想要 div 的样式与按钮完全一样。我注意到当我给按钮一个特定的高度时,文本总是垂直居中。

到目前为止,我尝试深入研究 Chromium 用户代理样式表,但没有成功。 -webkit-appereance: button也没成功

这是问题的演示:https://codepen.io/franzskuffka/pen/QzqKQx。请注意,行内块样式确保文本垂直对齐 - 边界框仍然很奇怪。

哪个 属性 使文本垂直居中而不需要任何额外的包装?这是怎么回事?

如果您的按钮没有固定高度,您可以向 div 添加填充以使文本垂直居中。添加 text-align: center; 使文本水平居中。

.btn {
  background-color: #000;
  color: #fff;
  padding: 10px;
  text-align: center;
}
<div class="btn">Hello!</div>

对于固定高度的按钮,您可能需要有一个子元素。

.parent {
  background-color: #000;
  color: #fff;
  height: 100px;
  text-align: center;
  width: 100px;
}

.child {
  top: 50%;
  transform: translateY(-50%);
}
<div class="parent">
  <div class="child">Hello!</div>
</div>

还有其他几种方法,但这些是我常用的方法。 CSS-如果您想尝试更多方法,Tricks 有关于 CSS 居中的完整指南:https://css-tricks.com/centering-css-complete-guide/.

TL;DR: 无法 使用 CSS 重新创建由 <button> 元素创建的布局。或者至少它隐藏得很好。

我通过将 <button> 上的显示值更改为 flex 来测试它,它影响了垂直对齐。 display:block 等其他值没有影响。似乎没有 css 值,这只是默认行为,无法为 div.

执行此操作

和你一样,我也在寻找这个问题的答案。我试图找到 css 属性 ,它在按钮中垂直居中内容。当我几乎要放弃时,我决定翻阅 html 规范,这是我发现的:

If the element is an input element, or if it is a button element and its computed value for 'display' is not 'inline-grid', 'grid', 'inline-flex', or 'flex', then the element's box has a child anonymous button content box with the following behaviors:

  1. The box is a block-level block container that establishes a new block formatting context (i.e., 'display' is 'flow-root').
  2. If the box does not overflow in the horizontal axis, then it is centered horizontally.
  3. If the box does not overflow in the vertical axis, then it is centered vertically. Otherwise, there is no anonymous button content box.

https://html.spec.whatwg.org/multipage/rendering.html#button-layout