【问题标题】:Vertically align a div in the middle of a Bootstrap 4.1 container-fluid > row > col [duplicate]垂直对齐Bootstrap 4.1容器中间的div-流体>行>列[重复]
【发布时间】:2019-05-21 17:26:54
【问题描述】:

我正在尝试将 Bootstrap 4.1 的 align-middle 应用到 row 内的 col。但它里面的内容似乎与顶部保持一致。这是我的代码:

<body class="d-flex">
  <div class="container-fluid">
    <a class="my-container" href="#">
      <div class="row">
        <div class="col flex-grow-1">
          Line 1<br>Line 2<br>Line 3
        </div>
        <div class="col-auto text-right align-middle">
          <i class="fas fa-chevron-right"></i>
        </div>
      </div>
    </a>
  </div>
</body>

这是一个显示结果的sn-p:

<link href="https://use.fontawesome.com/releases/v5.4.2/css/all.css" rel="stylesheet"/>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<body class="d-flex">
  <div class="container-fluid">
    <a class="my-container" href="#">
      <div class="row">
        <div class="col flex-grow-1">
          Line 1<br>Line 2<br>Line 3
        </div>
        <div class="col-auto text-right align-middle">
          <i class="fas fa-chevron-right"></i>
        </div>
      </div>
    </a>
  </div>
</body>

如何正确对齐图标?

【问题讨论】:

  • 你能把你的css代码也发过来吗?
  • @Comé 没有自定义 CSS 代码。这都是 Bootstrap(和一个 Font Awesome 图标)。我自己的 my-container 类没有附加任何样式。
  • 没问题。请看下面的答案。让我知道它是否对您有用,或者您是否仍需要帮助。

标签: html css bootstrap-4 vertical-alignment


【解决方案1】:

您可以在列上使用 Bootstrap 4 的 my-auto 类。代码如下:

html:

<div class="container-fluid">
  <a class="my-container" href="#">
  <div class="row">
    <div class="col flex-grow-1 my-auto">
      <p>line 1</p>
      <p>line 1</p>
      <p>line 1</p>
    </div>
  <div class="col-auto text-right">
  <i class="fas fa-chevron-right"></i>
</div>

css:

p {
  margin: 16px;
}

该段落的边距底部为1rem,因此您可以删除边距,也可以像我一样只给它一个整体边距。这对我来说很好。

【讨论】:

  • 天才 :-) 不过,请注意,在您上面的示例代码中,您已将 my-auto 添加到错误的 col 中。
  • 哦,我知道您希望 &lt;i&gt; 对齐。同样的原则适用:)。如果您不介意,请您也给它一个赞成票,以确保正确答案在顶部。
【解决方案2】:

尝试用span 包装你的i 并让span 拥有align-middle

【讨论】:

  • 对不起@CodeRed,它似乎没有什么不同。
  • @JohnSmith1976 你想在哪里添加图标?是在线路旁边还是某处?
  • 我希望图标的顶部和底部距离相等。如此对齐中心。但不要赶上图标。它可能是一些文本。重要的部分是将内容居中。
【解决方案3】:

您可以给row 一个固定的高度,然后相应地调整您的col 行高。请看下面的代码:

html:

<div class="container-fluid">
<a class="my-container" href="#">
  <div class="row">
    <div class="col flex-grow-1">
      Line 1<br>Line 2<br>Line 3
    </div>
    <div class="col-auto text-right">
      <i class="fas fa-chevron-right"></i>
    </div>
  </div>
</a>

css:

.row {
 height: 150px;
}

.col {
 line-height: 50px;
}

如果您的列中只有一行,则可以使列的行高与行高相同。您现在有三行,因此将行高除以三。

【讨论】:

  • @Comé 答案假定我的行将始终保持相同的高度。我需要它的高度来适应内容。
  • 好的,我对你的问题有不同的答案。我现在将创建一个新答案。
猜你喜欢
  • 2017-10-21
  • 2014-10-18
  • 1970-01-01
  • 2017-12-10
  • 2015-10-19
  • 1970-01-01
  • 2014-06-24
  • 2018-10-24
  • 1970-01-01
相关资源
最近更新 更多