michaelmcgurk
michaelmcgurk

Reputation: 6509

How to vertically center a Bootstrap container?

How do I vertically center this Bootstrap container div? I want it so I view the page it centers vertically on the page with black above and below my div.

Demo: https://jsfiddle.net/yunr225g/

HTML:

<div class="container">
  <div class="row">
    <div class="col-md-6 text-center">
      <img src="http://placehold.it/250x250">
      <button type="submit">Stay</button>
    </div>
    <div class="col-md-6 text-center">
      <img src="http://placehold.it/250x250">
      <button type="submit">Leave</button>
    </div>
  </div>
</div>

CSS:

body {
  margin: 10px;
  background:black;
}
button {
  display:block;
  text-align:center;
  margin:0 auto;
  margin:60px auto;
  background:black;
  border:2px solid #ffca00;
  padding:30px;
  width:250px;
  color:#ffca00;
  text-transform:uppercase;
}

Upvotes: 0

Views: 1019

Answers (1)

Stickers
Stickers

Reputation: 78676

First, you'll have to set all the parent elements of the container to height:100%, or use height:100vh directly. Then, use the position + transform tricks to center it vertically.

This works good on larger screens, you might need to tweak it via media queries + break points for smaller screens.

html, body {
  height: 100%;
}
body {
  margin: 0;
  background: black;
}
.container {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  border: 1px solid red;
}

jsFiddle

Or, try this CSS table approach, it seems to be working good, and doesn't affect Bootstrap grid. Note, added two extra divs as wrappers.

html, body {
  height: 100%;
}
body {
  margin: 0;
  background: black;
}
.container1 {
  display: table;
  width: 100%;
  height: 100%;
}
.container2 {
  display: table-cell;
  vertical-align: middle;
}

jsFiddle

Upvotes: 1

Related Questions