Html 如何在 Bootstrap 中垂直居中容器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22196587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 01:07:58  来源:igfitidea点击:

How to vertically center a container in Bootstrap?

htmlcsstwitter-bootstraptwitter-bootstrap-3vertical-alignment

提问by user1012181

I'm looking for a way to vertically center the containerdiv inside the jumbotronand to set it in the middle of the page.

我正在寻找一种将containerdiv垂直居中的方法,jumbotron并将其设置在页面中间。

The .jumbotronhas to be adapted to the full height and width of the screen. The .containerdiv has a width of 1025pxand should be in the middle of the page (vertically center).

.jumbotron必须适应于屏幕的整个高度和宽度。的.containerdiv有一个宽度1025px和应在该页面(垂直中心)的中间。

I want this page to have the jumbotron adapted to the height and width of the screen along with the container vertically center to the jumbotron. How can I achieve it?

我希望这个页面让大屏幕适应屏幕的高度和宽度以及容器垂直居中到大屏幕。我怎样才能实现它?

.jumbotron {
  height:100%;
  width:100%;
}
.container {
  width:1025px;
}
.jumbotron .container {
  max-width: 100%;
} 
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="jumbotron">
    <div class="container text-center">
        <h1>The easiest and powerful way</h1>
        <div class="row">
            <div class="col-md-7">
                 <div class="top-bg"></div>
            </div>

            <div class="col-md-5 iPhone-features" style="margin-left:-25px;">
                <ul class="top-features">
                    <li>
                        <span><i class="fa fa-random simple_bg top-features-bg"></i></span>
                        <p><strong>Redirect</strong><br>Visitors where they converts more.</p>
                    </li>
                    <li>
                        <span><i class="fa fa-cogs simple_bg top-features-bg"></i></span>
                        <p><strong>Track</strong><br>Views, Clicks and Conversions.</p>
                    </li>
                    <li>
                        <span><i class="fa fa-check simple_bg top-features-bg"></i></span>
                        <p><strong>Check</strong><br>Constantly the status of your links.</p>
                    </li>
                    <li>
                        <span><i class="fa fa-users simple_bg top-features-bg"></i></span>
                        <p><strong>Collaborate</strong><br>With Customers, Partners and Co-Workers.</p>
                    </li>
                        <a href="pricing-and-signup.html" class="btn-primary btn h2 lightBlue get-Started-btn">GET STARTED</a>
                        <h6 class="get-Started-sub-btn">FREE VERSION AVAILABLE!</h6>
                </ul>
            </div>
        </div>
    </div>
</div>

回答by Hashem Qolami

The Flexible box way

灵活的盒子方式

Vertical alignmentis now very simple by the use of Flexible box layout. Nowadays, this method is supported in a wide rangeof web browsers except Internet Explorer 8 & 9. Therefore we'd need to use some hacks/polyfillsor different approachesfor IE8/9.

通过使用灵活的框布局,垂直对齐现在非常简单。如今,这种方法在支持宽范围的不同之处的Internet Explorer 8&9的网络浏览器。因此我们需要使用一些黑客/ polyfills不同的方法用于IE8 / 9。

In the following I'll show you how to do that in only 3 linesof text (regardless of old flexbox syntax).

在下面,我将向您展示如何仅用3 行文本(不管旧的 flexbox 语法)来做到这一点。

Note:it's better to use an additional class instead of altering .jumbotronto achieve the vertical alignment. I'd use vertical-centerclass name for instance.

注意:最好使用额外的类而不是改变.jumbotron来实现垂直对齐。例如,我会使用vertical-center类名。

Example Here(A Mirroron jsbin).

实施例在此(A镜子上jsbin)

<div class="jumbotron vertical-center"> <!-- 
                      ^--- Added class  -->
  <div class="container">
    ...
  </div>
</div>
.vertical-center {
  min-height: 100%;  /* Fallback for browsers do NOT support vh unit */
  min-height: 100vh; /* These two lines are counted as one :-)       */

  display: flex;
  align-items: center;
}

Importantnotes (Considered in the demo):

重要说明(在演示中考虑)

  1. A percentagevalues of heightor min-heightproperties is relative to the heightof the parent element, therefore you should specify the heightof the parent explicitly.

  2. Vendor prefixed / old flexbox syntax omitted in the posted snippet due to brevity, but exist in the online example.

  3. In some of old web browsers such as Firefox 9 (in which I've tested), the flex container - .vertical-centerin this case - won't take the available space inside the parent, therefore we need to specify the widthproperty like: width: 100%.

  4. Also in some of web browsers as mentioned above, the flex item - .containerin this case - may not appear at the center horizontally. It seems the applied left/right marginof autodoesn't have any effect on the flex item.
    Therefore we need to align it by box-pack / justify-content.

  1. 一个百分比heightmin-height性质是相对height父元素的,因此,你应该指定height明确的母公司。

  2. 由于简洁,在发布的代码段中省略了供应商前缀/旧的 flexbox 语法,但存在于在线示例中。

  3. 在一些旧的 Web 浏览器中,例如 Firefox 9 (我已经测试过),flex 容器 -.vertical-center在这种情况下 - 不会占用父级内部的可用空间,因此我们需要指定如下width属性:width: 100%

  4. 同样在上面提到的一些 web 浏览器中,flex 项目 -.container在这种情况下 - 可能不会水平出现在中心。看来所施加的左/右marginauto没有在柔性项目产生任何影响。
    因此我们需要将它对齐box-pack / justify-content

For further details and/or vertical alignment of columns, you could refer to the topic below:

有关列的更多详细信息和/或垂直对齐,您可以参考以下主题:



The traditional way for legacy web browsers

传统 Web 浏览器的传统方式

This is the old answer I wrote at the time I answered this question. This method has been discussed hereand it's supposed to work in Internet Explorer 8 and 9 as well. I'll explain it in short:

这是我在回答这个问题时写的旧答案。此方法已在此处讨论,它应该也适用于 Internet Explorer 8 和 9。我将简要解释一下:

In inline flow, an inline level element can be aligned vertically to the middle by vertical-align: middledeclaration. Spec from W3C:

在内联流中,内联级别元素可以通过vertical-align: middle声明垂直居中对齐。规格从W3C

middle
Align the vertical midpoint of the box with the baseline of the parent box plus half the x-height of the parent.

middle
将框的垂直中点与父框的基线加上父框 x 高度的一半对齐。

In cases that the parent - .vertical-centerelement in this case - has an explicit height, by any chance if we could have a child element having the exact same heightof the parent, we would be able to move the baseline of the parentto the midpoint of the full-height child and surprisingly make our desired in-flow child - the .container- aligned to the center vertically.

在案件父-.vertical-center元素在这种情况下-有一个明确的height,以任何机会,如果我们能有具有完全相同的一个子元素height的父,我们将能够于母公司的基线移动到完整的中点-height 子项并令人惊讶地使我们想要的流入子项 - .container- 垂直对齐中心。

Getting all together

聚在一起

That being said, we could create a full-height element within the .vertical-centerby ::beforeor ::afterpseudo elements and also change the default displaytype of it and the other child, the .containerto inline-block.

话虽如此,我们可以在.vertical-centerby::before::after伪元素中创建一个全高元素,并更改display它和另一个子元素的默认类型 .containerto inline-block

Then use vertical-align: middle;to align the inline elements vertically.

然后用于vertical-align: middle;垂直对齐内联元素。

Here you go:

干得好:

<div class="jumbotron vertical-center">
  <div class="container">
    ...
  </div>
</div>
.vertical-center {
  height:100%;
  width:100%;

  text-align: center;  /* align the inline(-block) elements horizontally */
  font: 0/0 a;         /* remove the gap between inline(-block) elements */
}

.vertical-center:before {    /* create a full-height inline block pseudo=element */
  content: " ";
  display: inline-block;
  vertical-align: middle;    /* vertical alignment of the inline element */
  height: 100%;
}

.vertical-center > .container {
  max-width: 100%;

  display: inline-block;
  vertical-align: middle;  /* vertical alignment of the inline element */
                           /* reset the font property */
  font: 16px/1 "Helvetica Neue", Helvetica, Arial, sans-serif;
}

WORKING DEMO.

工作演示

Also, to prevent unexpected issues in extra small screens, you can reset the height of the pseudo-element to autoor 0or change its displaytype to noneif needed so:

此外,为了防止在超小屏幕中出现意外问题,您可以根据需要将伪元素的高度重置为auto0或将其display类型更改为none

@media (max-width: 768px) {
  .vertical-center:before {
    height: auto;
    /* Or */
    display: none;
  }
}

UPDATED DEMO

更新的演示

And one more thing:

还有一件事情:

If there are footer/headersections around the container, it's better to position that elements properly (relative, absolute? up to you.)and add a higher z-indexvalue (for assurance) to keep them always on the top of the others.

如果容器周围有footer/header部分,最好正确放置这些元素relative, absolute? 由您决定。)并添加更高的z-index值(为了保证)以保持它们始终位于其他元素的顶部。

回答by Zim

Update 2019

2019 年更新

Bootstrap 4includes flexbox, so the method of vertical centering is much easier and doesn't require extra CSS.

Bootstrap 4包含 flexbox,因此垂直居中的方法要容易得多,并且不需要额外的 CSS

Just use the d-flexand align-items-centerutility classes..

只需使用d-flexalign-items-center实用程序类..

<div class="jumbotron d-flex align-items-center">
  <div class="container">
    content
  </div>
</div>

http://www.codeply.com/go/ui6ABmMTLv

http://www.codeply.com/go/ui6ABmMTLv

Important:Vertical centering is relative to height. The parent container of the items you're attempting to center musthave a defined height. If you want the height of the page use vh-100or min-vh-100on the parent! For example:

重要提示:垂直居中是相对于 height 的。您尝试居中的项目的父容器必须具有定义的 height。如果您想要页面的高度,请使用vh-100min-vh-100在父级上!例如:

<div class="jumbotron d-flex align-items-center min-vh-100">
  <div class="container text-center">
    I am centered vertically
  </div>
</div>



另见: Vertical Align Center in Bootstrap 4Bootstrap 4 中的垂直对齐中心

回答by Rontuku

add Bootstrap.css then add this to your css

添加 Bootstrap.css 然后将其添加到您的 css

   
html, body{height:100%; margin:0;padding:0}
 
.container-fluid{
  height:100%;
  display:table;
  width: 100%;
  padding: 0;
}
 
.row-fluid {height: 100%; display:table-cell; vertical-align: middle;}
 
 

.centering {
  float:none;
  margin:0 auto;
}
Now call in your page 

<div class="container-fluid">
    <div class="row-fluid">
        <div class="centering text-center">
           Am in the Center Now :-)
        </div>
    </div>
</div>

回答by Rontuku

In Bootstrap 4:

Bootstrap 4 中

to center the child horizontally, use bootstrap-4 class:

水平居中的孩子,使用引导-4类:

justify-content-center

to center the child vertically, use bootstrap-4 class:

垂直居中孩子,请使用 bootstrap-4 类:

 align-items-center

but remember don't forget to use d-flexclass with these it's a bootstrap-4 utility class, like so

但请记住不要忘记使用d-flex类,它是一个 bootstrap-4 实用程序类,就像这样

<div class="d-flex justify-content-center align-items-center" style="height:100px;">
    <span class="bg-primary">MIDDLE</span>    
</div>

Note:make sure to add bootstrap-4 utilities if this code does not work

注意:如果此代码不起作用,确保添加 bootstrap-4 实用程序

I know it's not the direct answer to this question but it may help someone

我知道这不是这个问题的直接答案,但它可能会帮助某人

回答by John Slegers

My prefered technique :

我喜欢的技术:

body {
  display: table;
  position: absolute;
  height: 100%;
  width: 100%;
}

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


Demo

演示

body {
  display: table;
  position: absolute;
  height: 100%;
  width: 100%;
}

.jumbotron {
   display: table-cell;
   vertical-align: middle;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<div class="jumbotron vertical-center">
  <div class="container text-center">
    <h1>The easiest and powerful way</h1>
    <div class="row">
      <div class="col-md-7">
        <div class="top-bg">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
      </div>

      <div class="col-md-5 iPhone-features">
        <ul class="top-features">
          <li>
            <span><i class="fa fa-random simple_bg top-features-bg"></i></span>
            <p><strong>Redirect</strong><br>Visitors where they converts more.</p>
          </li>
          <li>
            <span><i class="fa fa-cogs simple_bg top-features-bg"></i></span>
            <p><strong>Track</strong><br>Views, Clicks and Conversions.</p>
          </li>
          <li>
            <span><i class="fa fa-check simple_bg top-features-bg"></i></span>
            <p><strong>Check</strong><br>Constantly the status of your links.</p>
          </li>
          <li>
            <span><i class="fa fa-users simple_bg top-features-bg"></i></span>
            <p><strong>Collaborate</strong><br>With Customers, Partners and Co-Workers.</p>
          </li>
          <a href="pricing-and-signup.html" class="btn-primary btn h2 lightBlue get-Started-btn">GET STARTED</a>
          <h6 class="get-Started-sub-btn">FREE VERSION AVAILABLE!</h6>
        </ul>
      </div>
    </div>
  </div>
</div>

See also this Fiddle!

另见这个小提琴

回答by MartinPicker

Tested in IE, Firefox, and Chrome.

在 IE、Firefox 和 Chrome 中测试。

.parent-container {
    position: relative;
    height:100%;
    width: 100%;
}

.child-container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
<div class="parent-container">
    <div class="child-container">
        <h2>Header Text</h2>
        <span>Some Text</span>
    </div>
</div>

Found on https://css-tricks.com/centering-css-complete-guide/

https://css-tricks.com/centering-css-complete-guide/ 上找到

回答by Ramil Gilfanov

for bootstrap4vertical center of few items

用于bootstrap4几个项目的垂直中心

d-flexfor flex rules

d-flex用于 flex 规则

flex-columnfor vertical direction on items

项目垂直方向的flex-column

justify-content-centerfor centering

justify-content-center用于居中

style='height: 300px;'must have for set points where center be calc or use h-100class

样式='高度:300px;' 必须具有中心为 calc 或使用h-100类的设置点

then for horizontal center div d-flex justify-content-centerand some container

然后对于水平中心div d-flex justify-content-center和一些容器

so we have hierarhy of 3 tag: div-column -> div-row -> div-container

所以我们有 3 个标签的层次结构:div-column -> div-row -> div-container

     <div class="d-flex flex-column justify-content-center bg-secondary" 
        style="height: 300px;">
        <div class="d-flex justify-content-center">
           <div class=bg-primary>Flex item</div>
        </div>
        <div class="d-flex justify-content-center">
           <div class=bg-primary>Flex item</div>
        </div>
      </div> 

回答by David Martinez Esguerra

If you're using Bootstrap 4, you just have to add 2 divs:

如果您使用的是 Bootstrap 4,则只需添加 2 个 div:

.jumbotron{
  height:100%;
  width:100%;
}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>    
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>

<body>
  <div class="jumbotron">
    <div class="d-table w-100 h-100">
      <div class="d-table-cell w-100 h-100 align-middle">
        <h5>
          your stuff...
        </h5>
        <div class="container">
          <div class="row">
            <div class="col-12">
              <p>
                More stuff...
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>

The classes: d-table, d-table-cell, w-100, h-100 and align-middle will do the job

类:d-table、d-table-cell、w-100、h-100 和 align-middle 将完成这项工作

回答by pierre abi chacra

Give the container class

给容器类

.container{
    height: 100vh;
    width: 100vw;
    display: flex;
}

Give the div that's inside the container:

给出容器内的 div:

align-content: center;

All the content inside this div will show up in the middle of the page.

此 div 中的所有内容都将显示在页面中间。

回答by Mohan Dere

Here is the way which I am using for align content vertically - top/center/bottom with bootstrap 3 rows. Bootstrap 3 columns with same height and vertically aligned.

这是我用于垂直对齐内容的方式 - 顶部/中心/底部与引导程序 3 行。Bootstrap 3 列具有相同的高度并垂直对齐。

/* columns of same height styles */

.row-full-height {
  height: 100%;
}
.col-full-height {
  height: 100%;
  vertical-align: middle;
}
.row-same-height {
  display: table;
  width: 100%;
  /* fix overflow */
  table-layout: fixed;
}
.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;
  }
}
/* vertical alignment styles */

.col-top {
  vertical-align: top;
}
.col-middle {
  vertical-align: middle;
}
.col-bottom {
  vertical-align: bottom;
<div class="container">

<h2>Demo 1</h2>
<div class="row">
  <div class="row-same-height">
    <div class="col-xs-3 col-xs-height">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tempus tincidunt porttitor. Praesent vehicula aliquam enim. Fusce non luctus eros, sit amet consequat velit. Pellentesque volutpat est et est imperdiet pharetra. Integer vestibulum feugiat malesuada. Proin a felis ut libero vestibulum fermentum ut sit amet est. Morbi placerat eget lacus sed sagittis. Nullam eu elit gravida arcu viverra facilisis. Quisque laoreet enim neque, ut consequat sem tincidunt at. Fusce lobortis scelerisque libero, eget vulputate neque. </div>
    <div class="col-xs-3 col-xs-height col-top">2st column</div>
    <div class="col-xs-3 col-xs-height col-middle">3st column</div>
    <div class="col-xs-3 col-xs-height col-bottom">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tempus tincidunt porttitor. Praesent vehicula aliquam enim. Fusce non luctus eros, sit amet consequat velit. Pellentesque volutpat est et est imperdiet pharetra.</div>
  </div>
</div><!-- ./row -->
</div><!-- ./container -->

Here is a JSFiddledemo.

这是一个JSFiddle演示。