垂直居中,父母高度可调

时间:2016-11-05 06:33:41

标签: html css twitter-bootstrap

我正在使用带有两个col-sm-6类列的Bootstrap框架。它们使用row-eq-height进行高度匹配,因为相邻列仅包含背景图像。

更新的代码:



section, .section-img {
 position: relative;
 background-size: cover;
 background-repeat: no-repeat;
 background-position: center center;
 margin: 0; padding: 0;
}

 .row-eq-height {
  min-height: 400px;
  display: flex;
 }

.col-sm-6 {
 flex: 1;
 display: flex;
 align-items: center;
}

.section-content {
 flex: 1;
 text-align: center;
}

<section class="row row-eq-height">
  <div class="col-sm-6">
    <div class="section-content">
      .... content of post ...
    </div>
  </div>

  <div class="col-sm-6 section-img" style="background-image:url('<?php ... image code ... ?>>
    ... image taking up all the space ....
  </div>

</section>
&#13;
&#13;
&#13;

代码居中并在高度增加时进行调整,但会移除图像高度(行的高度相等)。图像应该与它旁边的列一样高,所以图片显示

更新了输出:

enter image description here

2 个答案:

答案 0 :(得分:4)

由于您已经使用flexbox,因此您可以跳过position:absolute, transform: translate(),...部分来集中内容并使用flexbox自己的属性。

&#13;
&#13;
.row-eq-height {
  min-height: 400px;
  display: flex;
}
.col-sm-6 {
  flex: 1;
  display: flex;
  align-items: center;
}
.section-content {
  flex: 1;
  text-align: center;
}
.section-img {
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center center;
}
&#13;
<section class="row row-eq-height">
    <div class="col-sm-6">
      <div class="section-content">
        .... content of post ...
        <br> .... content of post ...
        <br> .... content of post ...
        <br> .... content of post ...
        <br> .... content of post ...
        <br> .... content of post ...
        <br> .... content of post ...
      </div>
    </div>
    <div class="col-sm-6 section-img" style="background-image: url(http://lorempixel.com/300/300/nature/1)">
    </div>
</section>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用css display:table选项,并且可以控制垂直对齐,顶部,中间,底部

HTML

<section class="row row-eq-height">
  <div class="content-tbl">
    <div class="content-tbl-cell"> Text-goes-here </div>
    <div class="content-tbl-cell"> Text-goes-here </div>
  </div>
</section>

CSS

.content-tbl {display:table;width:100%;}
.content-tbl-cell {display:table-cell;width:50%;vertical-align:middle;padding:0 15px;}