【问题标题】:Vertically align text across divs跨 div 垂直对齐文本
【发布时间】:2019-12-28 14:54:33
【问题描述】:

我很确定这是一个愚蠢的问题,但我无法弄清楚。我有两个并排的 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: top div 的顶部。

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

谢谢。

【问题讨论】:

    标签: html css


    【解决方案1】:

    我会使用弹性容器。在这种情况下,您的第一个 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

    【讨论】:

      【解决方案2】:

      这应该适合你。此代码将使每个标题的底部对齐,但是下划线基于字体大小,因此您无法真正考虑到这一点。

      <div class="headers">
          <div class="about-page-column">
              <h3>Experience</h3>
          </div>
          <div class="about-page-column">
              <h4>Links</h4>
          </div>
      </div>
      
      .headers {
          display: flex;
          align-items: baseline;
      
          .about-page-column {
              display: inline-block;
              vertical-align: top;
              width: 49%;
              margin-top: 5px;
              text-align: center;
              padding: 5px;
      
          h3,h4 {
             padding: 5px;
             font-family: 'Rubik', sans-serif;
             text-decoration: underline;
             color: $page-title-color;
          }
      
          h3 {
             font-size: 2em;
          }
      
          h4 {
              font-size: 1.5em;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2012-12-09
        • 1970-01-01
        • 2014-10-16
        • 2018-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-17
        • 2015-11-22
        相关资源
        最近更新 更多