在 Bootstrap 井中垂直居中 img

Vertically middle an img in a Bootstrap well

我一直在尝试将 img 放置在固定高度 div 的中间,但我做错了。我尝试了几种不同的变体来查看 SO 上的其他解决方案,但我想我遗漏了一些东西。

这是我的代码和代码片段:

// Style
.test-ht {
  min-height: 250px;
  vertical-align: middle;
}
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container">
  <div class="row">
    <div class="col-md-3 well test-ht">
      <img src="http://placehold.it/350x150" class="img-responsive" />
    </div>
  </div>
</div>

将像素高度添加到父级 div 包装您的 img div 和您的图像,例如 img-parent 并将 height: 100%display:inline-block; 添加到包装器 div 像这样:

.img-parent  {
    height: 250px;
}
.test-ht {
  height: 100%;
  vertical-align: middle;
  display:inline-block;
}

通过- How to vertically align an image inside div

I have been trying to place an img in the middle of a fixed height div.

div 中删除 class,并将 class 添加到 img。试试下面的代码片段。

// Style
.test-ht {
    width: 350px;
    height: 150px;
}

.test-ht:before {
    content: "";
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}

.test-ht :first-child {
    display:inline-block;
}
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container">
  <div class="row">
    <div class="col-md-3 well">
      <img class="img-responsive test-ht" src="http://placehold.it/350x150" />
    </div>
  </div>
</div>

尝试像这样更改 CSS:

.test-ht {
    position: relative;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}

我发现在大多数情况下,通过为每个位置使用一系列自定义 class 元素,可以很容易地将项目与 bootstrap 垂直对齐。

示例:

.align-middle {
display:table-cell;
vertical-align:middle;
float:none;
}

然后我将该自定义 class 应用到我希望在行中居中对齐的任何列。