如何垂直居中我的div

时间:2013-12-06 22:57:57

标签: css html center

我有一个三列div,并希望垂直居中第3个div(data_cell3)。我该怎么做?

无论文本区域有多大,我都希望它垂直居中对齐。

这是一个链接: http://jsfiddle.net/huskydawgs/UMf3k/89/

  <div class="wrapper-data">
<div class="data_row">
  <div class="data_cell1">
        <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
        </div> 
  <div class="data_cell2">

  </div>
    <div class="data_cell3">
        <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p>
  </div>
  </div>

2 个答案:

答案 0 :(得分:2)

.data_row{
    display:table;
}

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

这可能需要调整data_row的子节点的css,因为你的宽度最初可能会偏离,但实际上你可以通过这种方式实现垂直居中。

http://jsfiddle.net/UMf3k/92/

对于我们这些使用sass的人,我的同事通过添加scut为sass实用程序库做出了贡献,这使得它易于重用。致{}的David Clark致信。 scut用法示例:

@mixin vertically-center ($child: ".vcentered") {
  display: table;
  & > #{$child} {
    display: table-cell;
    vertical-align: middle;
  }
}

编辑: 通过使所有单元格显示:table-cell它将保持宽度,就像你拥有它们一样。目前,您正在使用显示内联块来混合浮动。

答案 1 :(得分:0)

.data_row {
    position:relative;
}

.data_cell3 {
    position:absolute;
    top:50%;
    height:5em; 
    margin-top:-2.5em; /* Half of above height */
}

jsFiddle demo

  • 将父容器指定为position:relative或position:absolute。
  • 在子容器上指定固定高度。
  • 设置位置:绝对值和顶部:子容器上的50%将顶部向下移动到父级的中间。
  • 设置margin-top:-yy,其中yy是子容器高度的一半,以抵消项目。

来源:http://phrogz.net/css/vertical-align/