【问题标题】:vertical align middle wont vertical align middle when the div is a fixed height [duplicate]当div是固定高度时,垂直对齐中间不会垂直对齐中间[重复]
【发布时间】:2021-12-13 20:35:14
【问题描述】:

见下文:

.fixed-height {
  height: 100px;
  background-color: green;
}

.fixed-height h1 {
  font-size: 14px;
  color: red;
  display: inline;
  vertical-align: middle;
}
<div class="fixed-height">
  <h1>VERTICAL ALIGN ME</h1>
</div>

https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align

vertical-align CSS 属性设置内联的垂直对齐方式, 内联块或表格单元框。

Vertically Align a Header Tag with Fixed Height through CSS

/* 
This https://stackoverflow.com/questions/14695857/vertically-align-a-header-tag-with-fixed-height-through-css

but it doesnt work either, it cuts the div short and isn't in the middle

*/

.fixed-height {
  height: 100px;
  background-color: green;
  display: inline-table
}

.fixed-height h1 {
  font-size: 14px;
  color: red;
  vertical-align: middle;
}
<div class="fixed-height">
  <h1>VERTICAL ALIGN ME</h1>
</div>
  1. 盒子怎么被剪短了?
  2. 怎么不会走到中间?

所以我知道我可以做到:

/* 
Flex Version
*/

.fixed-height {
  height: 100px;
  background-color: green;
  display: flex;
  align-items: center;
}

.fixed-height h1 {
  font-size: 14px;
  color: red;
  vertical-align: middle;
}
<div class="fixed-height">
  <h1>VERTICAL ALIGN ME</h1>
</div>

我做了什么来尽快完成这项工作......

但我想知道为什么垂直对齐在文档中所说的内联元素或内联框时不起作用。

【问题讨论】:

  • 请阅读manual / MDN WebDocs - vertical-aling 不能用于对齐块级元素,例如&lt;h1&gt;。它还与行高对齐,而不是整个父元素。
  • 您想知道为什么,但您接受了一个没有解释任何内容的答案?

标签: html css vertical-alignment


【解决方案1】:

您可以使用与容器高度相同的line-height 设置。这将使h1 垂直居中,无需任何进一步设置:

.fixed-height {
  height: 100px;
  background-color: green;
}

.fixed-height h1 {
  font-size: 14px;
  line-height: 100px;
  color: red;
}
<div class="fixed-height">
  <h1>VERTICAL ALIGN ME</h1>
</div>

【讨论】:

    猜你喜欢
    • 2015-05-26
    • 1970-01-01
    • 2017-10-21
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    • 1970-01-01
    相关资源
    最近更新 更多