Bootstrap 网格中列行的垂直对齐

2023-12-30

假设您有一个使用 Twitter Bootstrap 的两列布局,您希望其中特定的行彼此垂直对齐:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha/css/bootstrap.min.css"/>

<div class="container">
  <div class="row">
    <div class="col-sm-6">
      <h2>Column 1</h2>
      <p>Optional content of variable height.</p>
      <p><strong>Align this vertically...</strong></p>
    </div>
    <div class="col-sm-6">
      <h2>Column 2</h2>
      <p><strong>...with this</strong></p>
    </div>
  </div>
</div>

垂直对齐对于表格布局是可行的,但是,Bootstrap 列的大小调整和响应行为会丢失:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha/css/bootstrap.min.css">

<div class="container">
  <table class="row">
    <thead>
      <tr>
        <th scope="col"><h2>Column 1</h2></th>
        <th scope="col"><h2>Column 2</h2></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><p>Optional content of variable height.</p></td>
      </tr>
      <tr>
        <td><strong>Align this vertically...</strong></td>
        <td><strong>...with this</strong></td>
      </tr>
    </tbody>
  </table>
</div>

另一种选择是拆分行,但是,布局在较小的分辨率上以错误的顺序折叠。

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha/css/bootstrap.min.css">

<div class="container">
  <div class="row">
    <div class="col-sm-6">
      <h2>Column 1</h2>
    </div>
    <div class="col-sm-6">
      <h2>Column 2</h2>
    </div>
  </div>
  <div class="row">
    <div class="col-sm-6">
      <p>Optional content of variable height.</p>
    </div>
  </div>
  <div class="row">
    <div class="col-sm-6">
      <strong>Align this vertically...</strong>
    </div>
    <div class="col-sm-6">
      <strong>...with this</strong>
    </div>
  </div>
</div>

如何在保持 Bootstrap 列行为的同时获得相同的结果?使用表格布局是可行的方法还是死胡同?是否可以不借助 JavaScript 将行定位到计算的偏移量?

编辑:我的目标是让行的顶部对齐,就像表布局中的情况一样。


据我所知,我会测试这些解决方案。

解决方案1:使用Javascript(如果需要的话,可以使用Jquery)检测左侧和右侧div的高度,并告诉它们具有相同的高度。

您可以在第二个内容 div 上应用此解决方案,以使粗体文本上方的空格具有相同的高度。

或者在比较两者的高度后,根据需要在较小的 div 中添加.. 例如作为 margin-top (带有需要对齐的粗体文本)。

不管怎样,如果你有他们两个的身高,你就有足够的信息来找到方法。这里可以提供多种解决方案,我让您找到适合您的环境和需求的更好的解决方案。

<div class="container">
  <div class="row">
    <div class="col-sm-6 leftcolumn">
      <h2>Column 1</h2>
      <div class="astallas"><p>Optional content of variable height.</p></div>
      <p><strong>Align this vertically...</strong></p>
    </div>
    <div class="col-sm-6 rightcolumn">
      <h2>Column 2</h2>
      <div class="astallas"></div> // make this empty div have the same height that the left one with variable content
      <p><strong>...with this</strong></p>
    </div>
  </div>
</div>

解决方案2(但有些浏览器不兼容):使用 Flexbox http://flexboxfroggy.com/ https://css-tricks.com/snippets/css/a-guide-to-flexbox/ https://css-tricks.com/snippets/css/a-guide-to-flexbox/

我认为这两者都可以与引导程序一起使用,并且会尊重响应需求。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Bootstrap 网格中列行的垂直对齐 的相关文章

随机推荐