【问题标题】:Vertically align multiple lines with parent div将多行与父 div 垂直对齐
【发布时间】:2025-12-20 04:20:08
【问题描述】:

如何对齐中间 div,使两条线垂直居中?

.container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.second {
  text-align: left;
  flex-grow: 2;
}
img {
  margin-right: 20px;
}
<div class="container">
  <div>
    <img src="http://via.placeholder.com/75x75">
  </div>
  <div class="second">
   <h2>Please vertically center both</h2>
   <p>of us!</p>
  </div>
  <div>
   Right
  </div>
</div>

【问题讨论】:

  • Middle Div 已经垂直居中。您可以看到由于默认边距标题和段落元素在浏览器中呈现时的间距
  • 将此添加到您的代码中:* { margin: 0; padding: 0; }jsfiddle.net/27fdcaso

标签: html css flexbox centering


【解决方案1】:

添加h2,p{margin:0} 以删除h2p 标签的默认边距

.container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.second {
  text-align: left;
  flex-grow: 2;
}

img {
  margin-right: 20px;
}
h2,p{margin:0}
<div class="container">
  <div>
    <img src="http://via.placeholder.com/75x75">
  </div>
  <div class="second">
    <h2>Please vertically center both</h2>
    <p>of us!</p>
  </div>
  <div>
    Right
  </div>
</div>

【讨论】: