Bootstrap 4中的垂直对齐

5

我正在尝试让文本居中在图片上方。 我使用了mx-auto来水平居中我的叠加文本,并使用align-middle进行垂直对齐。但是垂直对齐没有起作用。 有人知道为什么吗?

  

  <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

      <div class="card ">
<img class="img-fluid card-img" src="https://snap-photos.s3.amazonaws.com/img-thumbs/960w/1U2EGZ07GU.jpg" alt="Deer in nature">
<div class="card-img-overlay d-flex">
  <div class="mx-auto">
<h4 class="card-title align-middle">Animal Farm</h4>
<h6 class="text align-middle">George Orwell</h6>
<p class="card-text align-middle">Tired of their servitude to man, a group of farm animals revolt and establish their own society...</p>
</div>
</div>
</div>

3个回答

10

只需使用my-auto即可实现垂直居中...

  <div class="card">
        <img class="img-fluid card-img" src="https://snap-photos.s3.amazonaws.com/img-thumbs/960w/1U2EGZ07GU.jpg" alt="Deer in nature">
        <div class="card-img-overlay d-flex">
            <div class="my-auto mx-auto text-center">
                <h4 class="card-title">Animal Farm</h4>
                <h6 class="text">George Orwell</h6>
                <p class="card-text">Tired of their servitude to man, a group of farm animals revolt and establish their own society...</p>
            </div>
        </div>
  </div>

http://codeply.com/go/ZQM4ANFcXC

align-middle可以在display: tabledisplay: inline元素上使用。

另请参阅类似问题


有没有什么理由不使用 my-auto mx-auto 而改用 m-auto 更好呢? - Lee
如果您想要水平和垂直居中,请使用 m-auto。我同时使用了这两个类,因为问题只涉及垂直居中,我想区分使用 my-auto 的情况。 - Carol Skelly

0
你不需要使用 .mx-auto,直接在父元素上使用 .justify-content-center.align-items-center.flex-column 即可。https://v4-alpha.getbootstrap.com/utilities/flexbox/

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />

<div class="card ">
  <img class="img-fluid card-img" src="https://snap-photos.s3.amazonaws.com/img-thumbs/960w/1U2EGZ07GU.jpg" alt="Deer in nature">
  <div class="card-img-overlay d-flex justify-content-center align-items-center flex-column">
      <h4 class="card-title align-middle">Animal Farm</h4>
      <h6 class="text align-middle">George Orwell</h6>
      <p class="card-text align-middle">Tired of their servitude to man, a group of farm animals revolt and establish their own society...</p>
  </div>
</div>


0

使用这段代码进行尝试,如下:

<div class="card ">
<img class="img-fluid card-img" src="https://snap-photos.s3.amazonaws.com/img-thumbs/960w/1U2EGZ07GU.jpg" alt="Deer in nature">
<div class="card-img-overlay d-flex">

<div class="mx-auto" style="margin-top: auto;margin-bottom: auto;">
<h4 class="card-title">Animal Farm</h4>
<h6 class="text">George Orwell</h6>
<p class="card-text">Tired of their servitude to man, a group of farm animals revolt and establish their own society...</p>
</div>

</div>
</div>

基本上只需将style="margin-top: auto;margin-bottom: auto;"添加到具有mx-auto类的div中。


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