在Bootstrap列表组中垂直对齐文本

6
我正在尝试使用Bootstrap 3中的list-group-item来实现文本和按钮的垂直对齐。我已经试过将父元素a设为display: table;,内部的div设置为display: table-cell;,以便使用vertical-align: middle
但上述方法并不能解决问题,在这里我创建了一个CodePen示例,以重现这个问题。

Although for some reason if I post the same code here in SO snippet it seems to be working. However, when I render that in my HTML document it won't work.

a {
  overflow: hidden;
  display: table;
}

a > div {
  display: table-cell; 
  vertical-align: middle; 
}

.btn {
  width: 100%;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="list-group">
    <!-- ngRepeat: value in results -->
    <a href="/store/products/testing" class="list-group-item search-product ng-scope" ng-repeat="value in results">
      <div class="media col-md-3">
        <figure class="pull-left">
          <img class="media-object img-rounded img-responsive" src="http://lorempixel.com/500/500" alt="Testing">
        </figure>
      </div>
      <div class="col-md-6">
        <h4 class="list-group-item-heading ng-binding"> Test product </h4>
        <p class="list-group-item-text ng-binding" ng-bind-html="value.short_description | to_trusted">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et…</p>
      </div>
      <div class="col-md-3 text-center">
        <div ng-controller="postDataToCartCtrl" class="ng-scope">
          <form url="store/addtocart" ng-submit="add(value.id, 1)" class="ng-pristine ng-valid">
            <input name="quantity" type="hidden" value="1">
            <button type="submit" class="btn btn-success">
              <span class="glyphicon glyphicon-shopping-cart"></span> Add to Cart
            </button>
          </form>
        </div>
      </div>
    </a>
    <!-- end ngRepeat: value in results -->

  </div>
</div>

2个回答

4

我稍微修改了你的CSS代码

CSS

a.list-group-item {
  overflow: hidden;
  display: table;
}

a.list-group-item > div {
  display: table-cell; 
  vertical-align: middle; 
  float:none;
}

请查看上面的代码。我使用了a.list-group-item {}代替a {},因为默认的bootstrap .list-group-item {}类正在覆盖display:table属性。


这个可以运行,但是当我尝试时,它使我的列表项变短了。不确定如何恢复长度。 - Jacob Beauchamp
@JacobBeauchamp 我不确定你为什么会遇到这个宽度问题。但如果你能创建一个 CodePen 或其他类似的东西,我可以帮你解决这个问题。 - Nilesh Mahajan

2

只需将div上的浮动属性去掉,即像这样:

a > div {
 float: none !important;
}

1
谢谢您的快速回复,尽量避免使用!important声明会更好!也许可以提高特异性值。 - cch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接