垂直居中div内的每个元素

时间:2015-11-20 00:10:28

标签: html css html5 twitter-bootstrap-3

以下是我的问题的示例演示

http://www.bootply.com/tkrs6G3GlG

基本上,我已经在左侧表单组中,并且每个我都有大文本提供一些信息,然后要求用户选择一些东西(例如,只有收音机,但也有下拉列表和复选框) 。我希望对于每个表单组,右侧的选项根据文本大小垂直对齐(在中间)。在上面的例子中,收音机位于顶部,但我希望它们位于相应的表格组中间。

我试过

  .vcenter{vertical-align:middle;
     }

但它不起作用。我也试过设置div的高度,其中包含选项

 .maxHeight{
       height:100%;
 }

但是div并没有变大。我尝试使用较大的高度和隐藏溢出,但不工作。 到目前为止只有使用

的东西
.vcenter{
      position:absolute;
      vertical-align: middle;
 }

但它只能在大屏幕上看起来很好,但在屏幕调整大小后,它会与文本重叠。

4 个答案:

答案 0 :(得分:0)

如果您的div位于另一个div中,请尝试

#my_div{
       margin-left: auto;
       margin-right: auto; 
       width: /*put_your_width*/;
}

如果是parent div

   #my_div{
         display: table;
         margin-right: auto;
         margin-left: auto;
   }

答案 1 :(得分:0)

有几种方法可以做到这一点。我通常使用这种方法...

HTML

<div> <p>Center this text</p> </div>

CSS

div{    
    position: relative;
    height: 500px;
    width: 500px;
    background: green;
    -webkit-transform-style: preserve-3d;
    -moz-transform-style: preserve-3d;
    transform-style: preserve-3d;
p{
    position: absolute;
    top:50%;
    text-align:center;
    display:inline-block;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}

答案 2 :(得分:0)

我喜欢这样做的方式是添加margin: auto;以及上,左,右和下0,如下所示:

.parent {
    position: relative;
}

.child {
    margin: auto;
    position: absolute;
        top: 0; right: 0; bottom: 0; left: 0;
}

答案 3 :(得分:0)

你可以使用很多方法。

第一个是位置

    .parent_div{
          position:relative;
          width:500px;
          height:500px;
    }
    .children_div{
          position:absolute;
          width:100px;
          height:100px;
          left:0px;
          right:0px;
          top:0px;
          bottom:0px;
          margin:auto;
    }

- 但你需要指定子元素的高度和宽度..所以它不适合流体设计。

秒。 aproach是最好的我认为它使用显示:)

    .parent_div{
          display:table;
          width:500px;
          height:500px;
          text-align:center;
    }
    .children_div{
          display:table-cell;
          width:100%;
          height:100%;
          vertical-align:middle;

    }

    .children_children_div{
          /*What ever... this div will be centered verticaly*/

    }