如何在Bootstrap列中垂直居中div? [重复]

时间:2022-11-24 22:51:19

This question already has an answer here:

这个问题在这里已有答案:

I'm trying to vertically (and horizontally) center a div (height and width unknown) in a Bootstrap column. I can horizontally center the div by setting text-align to center. However I am struggling to vertically center the div. Here is a snippet of my code:

我正试图在Bootstrap列中垂直(和水平)居中div(高度和宽度未知)。我可以通过将text-align设置为center来水平居中div。但是我正在努力将div垂直居中。这是我的代码片段:

<div class="row">
    <div class="col-md-8 col-md-offset-2 col-xs-12">
        <div style="text-align: center"> <!--this works-->
            <p>Content goes here</p>                
        </div>
    </div>
</div>

Thanks in advance!

提前致谢!

2 个解决方案

#1


0  

If you're using Twitter Bootstrap and you have the Bootstrap 3, they added <div class="center-block">...</div>.

如果你使用Twitter Bootstrap并且你有Bootstrap 3,他们添加了

... 。

Reference: Bootstrap v3.1.1.

参考:Bootstrap v3.1.1。

#2


-1  

You may want to give this a shot:

你可能想要一试:

<div class="row">
   <div class="col-md-8 col-md-offset-2 col-xs-12 Outer">
      <div class="Inner>
         <p >Content goes here</p>                
      </div>
   </div>
</div>


/* CSS Code */

.Outer {
   border: 1px solid black;  /* Just so you can see it centered vertically */
   display: table-cell;
   height: 100%;
   min-height: 15em;    /* Set to height you need */
}
.Inner > p {
   vertical-align: middle;
   text-align: center;
   margin: 0 auto;
}

Keep in mind that the browser will automatically recognize the resolution width; however, the same functionality doesn't apply to height. You need to set a specified height on the outer element in order for the inner content to have something to vertically align itself to. Hope this helps!

请记住,浏览器会自动识别分辨率宽度;但是,相同的功能不适用于高度。您需要在外部元素上设置指定的高度,以便内部内容具有垂直对齐的内容。希望这可以帮助!

#1


0  

If you're using Twitter Bootstrap and you have the Bootstrap 3, they added <div class="center-block">...</div>.

如果你使用Twitter Bootstrap并且你有Bootstrap 3,他们添加了

... 。

Reference: Bootstrap v3.1.1.

参考:Bootstrap v3.1.1。

#2


-1  

You may want to give this a shot:

你可能想要一试:

<div class="row">
   <div class="col-md-8 col-md-offset-2 col-xs-12 Outer">
      <div class="Inner>
         <p >Content goes here</p>                
      </div>
   </div>
</div>


/* CSS Code */

.Outer {
   border: 1px solid black;  /* Just so you can see it centered vertically */
   display: table-cell;
   height: 100%;
   min-height: 15em;    /* Set to height you need */
}
.Inner > p {
   vertical-align: middle;
   text-align: center;
   margin: 0 auto;
}

Keep in mind that the browser will automatically recognize the resolution width; however, the same functionality doesn't apply to height. You need to set a specified height on the outer element in order for the inner content to have something to vertically align itself to. Hope this helps!

请记住,浏览器会自动识别分辨率宽度;但是,相同的功能不适用于高度。您需要在外部元素上设置指定的高度,以便内部内容具有垂直对齐的内容。希望这可以帮助!