TheOne
TheOne

Reputation: 11

Vertically centering text in a container when using Bootstrap?

I have been struggling for the last couple of days trying to figure out how to properly center text vertically. There is also a full-width background image.

I would like the text to stay centered no matter what height the enclosing container is.

Here is the code I have so far:

HTML:

<header class="thank-you">
  <div class="container">
    <div class="row">
      <div class="col-md-12">
        <div class="thank-you-message">
          <h1>Thank you</h1>
        </div>
      </div>
    </div>
  </div>
</header>

CSS:

.thank-you {
  text-align: center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  -o-background-size: cover;
  background: #000000;
  height: 500px;
}
.thank-you-message h1 {
  color: #FFFFFF;
}

Upvotes: 0

Views: 227

Answers (3)

Grzegorz Palian
Grzegorz Palian

Reputation: 349

The most versatile solution is using flexbox:

.thank-you-message{
  display: flex;
  justify-content: center;
  align-items: center;
}

Upvotes: 1

marcelo2605
marcelo2605

Reputation: 2794

You can use translate:

h1{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  margin: 0;  
}

https://jsfiddle.net/4ehmpdq5/

Upvotes: 3

baao
baao

Reputation: 73271

You can simply add

line-height:500px;
vertical-align:middle;

to your css:

.thank-you {
  text-align: center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
  -o-background-size: cover;
  background: #000000;
  height: 500px;
    line-height:500px;
    vertical-align:middle;
}

See this

fiddle

Upvotes: 1

Related Questions