如何在Bootstrap 4中垂直对齐项目?

时间:2018-10-10 20:39:31

标签: css twitter-bootstrap vertical-alignment

我正在尝试在列内垂直对齐文本。如果我在父级(列)中使用my-auto,则它会垂直对齐文本,但会将所有内容拉到中心,因此我需要保持背景。当前背景色在该列上。

当我删除my-auto时,将返回完整的橙色背景,但文本在顶部。

我试图创建一个内部row> column结构来解决这个问题,但是它不起作用。有什么想法吗?

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container-fluid">
  <div class="row no-gutters">
    <div class="col-xs-6 col-sm-4 col-md-3 col-lg-4 col-xl-4 my-auto" style="background-color: #f04e23;">
      <h1 class="display-4 text-center">2018 Speakers</h1>
    </div> 
    <div class="col-xs-6 col-sm-4 col-md-3 col-lg-2 col-xl-2">
      <div class="card">
        <img class="img-fluid" src="https://picsum.photos/400/600" alt="" />
      </div>
    </div>
    <div class="col-xs-6 col-sm-4 col-md-3 col-lg-2 col-xl-2">
      <div class="card">
        <img class="img-fluid" src="https://picsum.photos/400/600" alt="" />
      </div>
    </div>
    <div class="col-xs-6 col-sm-4 col-md-3 col-lg-2 col-xl-2">
      <div class="card">
        <img class="img-fluid" src="https://picsum.photos/400/600" alt="" />
      </div>
    </div>
    <div class="col-xs-6 col-sm-4 col-md-3 col-lg-2 col-xl-2">
      <div class="card">
        <img class="img-fluid" src="https://picsum.photos/400/600" alt="" />
      </div>
    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:2)

通过使用.d-flex类,然后使用.align-items-center类将文本垂直居中,而不是使用边距来将列的显示设置为flex。然后,您还可以添加.justify-content-center使其水平居中:

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container-fluid">
  <div class="row no-gutters">
    <div class="col-xs-6 col-sm-4 col-md-3 col-lg-4 col-xl-4 d-flex align-items-center justify-content-center" style="background-color: #f04e23;">
      <h1 class="display-4 text-center">2018 Speakers</h1>
    </div> 
    <div class="col-xs-6 col-sm-4 col-md-3 col-lg-2 col-xl-2">
      <div class="card">
        <img class="img-fluid" src="https://picsum.photos/400/600" alt="" />
      </div>
    </div>
    <div class="col-xs-6 col-sm-4 col-md-3 col-lg-2 col-xl-2">
      <div class="card">
        <img class="img-fluid" src="https://picsum.photos/400/600" alt="" />
      </div>
    </div>
    <div class="col-xs-6 col-sm-4 col-md-3 col-lg-2 col-xl-2">
      <div class="card">
        <img class="img-fluid" src="https://picsum.photos/400/600" alt="" />
      </div>
    </div>
    <div class="col-xs-6 col-sm-4 col-md-3 col-lg-2 col-xl-2">
      <div class="card">
        <img class="img-fluid" src="https://picsum.photos/400/600" alt="" />
      </div>
    </div>
  </div>
</div>