html - 如何垂直居中 Bootstrap 容器?

标签 html css twitter-bootstrap

如何垂直居中这个 Bootstrap 容器 div?我想要它,所以我查看页面时它在我的 div 上方和下方的页面上垂直居中。

演示: 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;
}

最佳答案

首先,您必须将容器的所有父元素设置为height:100%,或者直接使用height:100vh。然后,使用 position + transform 技巧使其垂直居中。

这在大屏幕上效果很好,您可能需要通过媒体查询和小屏幕断点来调整它。

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

jsFiddle

或者,尝试使用这种 CSS 表格方法,它似乎运行良好,并且不会影响 Bootstrap 网格。请注意,添加了两个额外的 div 作为包装器。

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

jsFiddle

关于html - 如何垂直居中 Bootstrap 容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38081820/

相关文章:

php - 上传某些文件时 $_FILES 和 $_POST 数据为空

css - Bootstrap 3 进度条百分比显示在它下面

html - CSS 中的扩展中间层

html - 为什么 border-radius 在 IE9 中不起作用?

javascript - Angularjs 动态对象更新

javascript - 按 esc 按键关闭 Bootstrap 弹出窗口

javascript - Chart js - 不获取响应图表中的高度

html - 为什么使用同一个数字z-index,后面的元素会重叠?

javascript - semantic-ui:使用 'doubling row' 类交错网格列行?

html - 媒体查询不起作用