如何在引导程序中垂直居中div?

时间:2015-10-20 22:44:09

标签: html css twitter-bootstrap

我有以下HTML代码:

<div class="text-center">
 <div class="row">
    <div class="col-md-6" id="centeredVertically">

        <div class="col-md-12">gdsgdsgdsgdshf</div> 
        <div class="col-md-12">gdsgdsgdsgdshf</div> 
        <div class="col-md-12">gdsgdsgdsgdshf</div> 
        <div class="col-md-12">gdsgdsgdsgdshf</div> 
        <div class="col-md-12">gdsgdsgdsgdshf</div> 
        <div class="col-md-12">gdsgdsgdsgdshf</div> 


    </div>
    <div class="col-md-6"><img src="http://cg.cs.uni-bonn.de/aigaion2root/attachments/poplar-leaves.png-fd1e71ded8cdc260ea04806113869bc3.png" alt="tree"></div>
</div>
    <h4>header.</h4>
    <p>hey there</p>
    <div class="paddown">

        <a class="btn btn-default" name="close" id="close" >Close</a>
    </div>
</div>

当您将网页调整到足够宽时 - 彼此相邻有两个div。我希望带有文本centeredVertically的div垂直居中于树的图片左侧。我尝试从其他堆栈溢出帖子中找到一个最佳答案,然后我将这个css类添加到我的div:

.vcenter {
    display: inline-block;
    vertical-align: middle;
    float: none;
}

但它并没有成功。我该如何解决?

我的小提琴在这里http://jsfiddle.net/2wujw71x/12/

感谢。

1 个答案:

答案 0 :(得分:1)

你可以使用这样的东西(使用表格):

HTML:

<div class="text-center">

  <div class="row row-same-height">

    <div class="col-md-6 col-md-height col-middle">

      <div>gdsgdsgdsgdshf</div> 
      <div>gdsgdsgdsgdshf</div> 
      <div>gdsgdsgdsgdshf</div> 
      <div>gdsgdsgdsgdshf</div> 
      <div>gdsgdsgdsgdshf</div> 
      <div>gdsgdsgdsgdshf</div> 

    </div>

    <div class="col-md-6  col-md-height col-middle">
      <img src="http://cg.cs.uni-bonn.de/aigaion2root/attachments/poplar-leaves.png-fd1e71ded8cdc260ea04806113869bc3.png" alt="cat">         
     </div>

  </div>

  <h4>Header</h4>

  <p>Hey there</p>

  <div class="paddown">
    <a class="btn btn-default" name="close" id="close" >Close</a>
  </div>

</div>

CSS:

.row-same-height {
  display: table;
  width: 100%;
}
.row-same-height.img-responsive {
  width: 100% !important;
  max-width: 100% !important;
}
.col-xs-height {
  display: table-cell;
  float: none !important;
}
@media (min-width: 768px) {
  .col-sm-height {
    display: table-cell;
    float: none !important;
  }
}
@media (min-width: 992px) {
  .col-md-height {
    display: table-cell;
    float: none !important;
  }
}
@media (min-width: 1200px) {
  .col-lg-height {
    display: table-cell;
    float: none !important;
  }
}
.col-top {
  vertical-align: top;
}
.col-middle {
  vertical-align: middle;
}
.col-bottom {
  vertical-align: bottom;
}

FIDDLE

此CSS允许您拥有相同高度的列,您可以将它们放在中间。这甚至可以在IE8上运行。

您可以在this page上了解详情。