首页 > 解决方案 > 跨 div 垂直对齐文本

问题描述

我很确定这是一个愚蠢的问题,但我无法弄清楚。我有两个并排的 div,具有不同大小的标题,我希望每个 div 中的顶部标题与基线对齐。但是vertical-align: baseline似乎不适用于跨div。这是我的代码(css 是 sass):

.about-page-column {
  display: inline-block;
  vertical-align: top;
  width: 49%;
  margin-top: 5px;
  text-align: center;
  padding: 5px;

  h3,h4 {
    padding: 5px;
    vertical-align: baseline; // this line obviously isn't doing anything
    font-family: 'Rubik', sans-serif;
    text-decoration: underline;
    color: $page-title-color;
  }

  h3 {
    font-size: 2em;
  }

  h4 {
    font-size: 1.5em;
  }
}
<div>
  <div class="about-page-column">
    <h3>Experience</h3>
  </div>
  <div class="about-page-column">
    <h4>Links</h4>
  </div>
</div>

这是结果。标题由它们的顶部对齐,因为它们浮动到vertical-align: topdiv 的顶部。

标题

如何在各自的 div 中对齐标题,以便它们与基线垂直对齐?如果这是不可能的,有什么解决方法?

谢谢。

标签: htmlcss

解决方案


我会使用弹性容器。在这种情况下,您的第一个 div

<div class="flex-container">
  <div class="about-page-column">
    <h3>Experience</h3>
  </div>
  <div class="about-page-column">
    <h4>Links</h4>
  </div>
</div>


.flex-container {
    display: flex;
    flex-direction: row; /*this is the default behavior of flex, you don't need to write it */
    justify-content: center;  /*This align the items horizontally*/
    align-items: center; /*This align the items vertically or you can use baseline*/
}

如果 flex-direction 设置为 column,justify-content 和 align-items 会交换它们的功能。

您可以在此处了解更多信息:

https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox

https://www.w3schools.com/css/css3_flexbox.asp


推荐阅读