Bootstrap 4垂直对齐文本无法在卡片上居中

23

尝试将下面卡片中的文本垂直居中:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

<div class="row text-center h-100">
  <div class="col-md-3 text-center my-auto">
    <div class="card card-block justify-content-center" style="height: 120px">
      <div class="card-body">
        This is some text within a card body.
      </div>
    </div>
  </div>
</div>

我非常清楚这里有许多类似的问题,但是我尝试了各种解决方案,但似乎都不能适用于我的卡片。

我在父级、卡片和卡片主体上尝试了“my-auto”。我尝试了“d-flex align-items-center h-100”和“justify-content-center”。还尝试了调整display属性。我错过了什么?

3个回答

70

这里是使用Bootstrap 4文档的解决方案,用于flexbox。在此处阅读更多信息

需要知道的内容:

d-flex -> 将元素设置为Flexbox。

align-items-center - 垂直对齐内容。

justify-content-center - 水平对齐内容。

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

<div class="row text-center h-100">
  <div class="col-md-3 text-center my-auto">
    <div class="card card-block d-flex" style="height: 120px">
      <div class="card-body align-items-center d-flex justify-content-center">
        This is some text within a card body.
      </div>
    </div>
  </div>
</div>


2
不错。我错过了在card-body中的d-flex,之前只在card类中使用它。 - tealowpillow
@tealowpillow 很高兴问题已经解决! - Naren Murali
@AjayKumar 很棒! - Naren Murali
@Naren Murali 很好。 - Riyaz

4

我错过了什么?

行高:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

<div class="row text-center h-100">
  <div class="col-md-3 text-center my-auto">
    <div class="card card-block justify-content-center" style="height: 120px; line-height:120px;">
      <div class="card-body">
        This is some text within a card body.
      </div>
    </div>
  </div>
</div>


不幸的是,当文本需要换行时,这对较小的框无效。 - tealowpillow

0

By this Way you can align card-title into center.

 .card-title-center{
        float: none !important;
    }
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

 <div class="card col-12 text-center">
    <div class="card-header bg-secondary">
        <h3 class="card-title card-title-center">Card Title</h3>
    </div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接