23

Trying to vertically align the text center in the following card:

<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>

I am fully aware of the many similar questions here, however I tried various solutions and none of them seems to work for my cards.

I tried "my-auto" on parent, card, and card-body. I tried "d-flex align-items-center h-100" and "justify-content-center". Also tried to play around with the display property. What am I missing?

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
tealowpillow
  • 419
  • 2
  • 10
  • 24

3 Answers3

70

Here is a solution using bootstrap 4 documentation for flexbox. Read more here

What you need to know,

d-flex -> makes the element a flexbox.

align-items-center - vertically aligns the content.

justify-content-center - horizontally aligns the content.

<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>
Naren Murali
  • 19,250
  • 3
  • 27
  • 54
4

What am I missing?

Line-height :

<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>
c-smile
  • 26,734
  • 7
  • 59
  • 86
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>
Kaleemullah
  • 446
  • 3
  • 8