Html Bootstrap 4 中的垂直对齐中心

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42252443/
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 14:23:45  来源:igfitidea点击:

Vertical Align Center in Bootstrap 4

htmlcsstwitter-bootstrapflexboxbootstrap-4

提问by canaan seaton

I am trying to center my Container in the middle of the page using Bootstrap 4. I have been unsuccessful thus far. Any help would be appreciated.

我正在尝试使用 Bootstrap 4 将我的 Container 置于页面中间。到目前为止我没有成功。任何帮助,将不胜感激。

I have built it at Codepen.ioso you guys can play with it and let me know what works as I am about out of ideas...

我已经在Codepen.io 上构建了它,所以你们可以玩它,让我知道什么是有效的,因为我没有想法......

var currentAuthor = "";
var currentQuote  = "";
function randomQuote() {
  $.ajax({
      url: "https://api.forismatic.com/api/1.0/?",
      dataType: "jsonp",
      data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
      success: function( response ) {
        $("#quote-content").html('<h2 id="quote-content" class="display-5"><i class="fa fa-quote-left" aria-hidden="true"> ' + response.quoteText + ' <i class="fa fa-quote-right" aria-hidden="true"></i></h2>');
        $("#quote-author").html('<p id="quote-author" class="lead"><em>' + response.quoteAuthor + '</em></p>');
        
        currentAuthor = response.quoteAuthor;
        currentQuote  = response.quoteText
      }
  });
}

function openURL(url){
  window.open(url,'Share', 'width=550, height=400, toolbar=0, scrollbars=1 ,location=0 ,statusbar=0,menubar=0, resizable=0');
}

function tweetQuote(){
      openURL('https://twitter.com/intent/tweet?hashtags=quotes,freecodecamp&related=freecodecamp&text=' + encodeURIComponent('"' + currentQuote + '" - ' + currentAuthor));
}

$(document).ready(function () {
    randomQuote();

    $("#get-another-quote-button").click(function(){
        randomQuote();
    });

   $('#tweet').on('click', function() {
       tweetQuote();
   });
});
html, body {
  background-image: url("https://www.mylinea.com/wp-content/uploads/beautiful-trees-stock-photo-055.jpg");
    background-color: #17234E;
    margin-bottom: 0;
    min-height: 30%;
    background-repeat: no-repeat;
    background-position: center;
    -webkit-background-size: cover;
    background-size: cover;
}


.btn-new-quote {
    color: #0C0C0D;
    background-color: transparent;
    border-color: #414147;
}

.btn-new-quote:hover {
    color: #0C0C0D;
    background-color: #9A989E;
    border-color: #0C0C0D;
}

#tweet {
    color: RGB(100, 100, 100);
}

#tweet:hover {
    color: RGB(50, 50, 50);
}


.jumbotron {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    opacity: .85;
    border-color:  RGB(50, 50, 50);
    padding-bottom: 8px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
<div class="container">
    <div class="row justify-content-center align-self-center">
        <div class="col-sm-6">
            <div class="jumbotron vertical-center text-center">
                <h2 id="quote-content" class="display-5"><i class="fa fa-quote-left" aria-hidden="true"></i><i class="fa fa-quote-right" aria-hidden="true"></i></h2>
                <p id="quote-author" class="lead"><em></em></p>
                <hr class="my-2">
                <div class="row align-items-center justify-content-between">
                    <div class="col-sm-1-4 text-left">
                        <a id="tweet" href="#">
                            <h2 class="display-4"><i class="fa fa-twitter" aria-hidden="true"></i></h2>
                        </a>
                    </div>
                    <div class="col-sm-1-4 text-right">
                        <button id="get-another-quote-button" type="button" class="btn btn-outline-secondary  btn-new-quote">Don't Quote Me on This...</button>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>

回答by Zim

Important!Vertical center is relative to the heightof the parent

重要的!垂直中心是相对于父级的高度

If the parent of the element you're trying to center has no defined height, noneof the vertical centering solutions will work!

如果你想中心元素的父一直没有明确的 高度没有垂直居中的解决方案将工作!

Now, onto vertical centering in Bootstrap 4...

现在,在 Bootstrap 4 中垂直居中......

You can use the new flexbox & size utilitiesto make the containerfull-height and display: flex. These options don't require extra CSS(except that the height of the container (ie:html,body) must be 100%).

您可以使用新的flexbox 和 size 实用程序来制作container全高和display: flex. 这些选项不需要额外的 CSS(除了容器高度 (ie:html,body) 必须是 100%)。

Option 1 align-self-centeron flexbox child

align-self-centerflexbox 子项上的选项 1

<div class="container d-flex h-100">
    <div class="row justify-content-center align-self-center">
     I'm vertically centered
    </div>
</div>

https://www.codeply.com/go/fFqaDe5Oey

https://www.codeply.com/go/fFqaDe5Oey

Option 2 align-items-centeron flexbox parent(.rowis display:flex; flex-direction:row)

align-items-centerflexbox 父项上的选项 2( .rowis display:flex; flex-direction:row)

<div class="container h-100">
    <div class="row align-items-center h-100">
        <div class="col-6 mx-auto">
            <div class="jumbotron">
                I'm vertically centered
            </div>
        </div>
    </div>
</div>

enter image description here

在此处输入图片说明

https://www.codeply.com/go/BumdFnmLuk

https://www.codeply.com/go/BumdFnmLuk

Option 3 justify-content-centeron flexbox parent(.cardis display:flex;flex-direction:column)

justify-content-centerflexbox 父项上的选项 3( .cardis display:flex;flex-direction:column)

<div class="container h-100">
    <div class="row align-items-center h-100">
        <div class="col-6 mx-auto">
            <div class="card h-100 border-primary justify-content-center">
                <div>
                    ...card content...
                </div>
            </div>
        </div>
    </div>
</div>

https://www.codeply.com/go/3gySSEe7nd

https://www.codeply.com/go/3gySSEE7nd



More on Bootstrap 4 Vertical Centering

有关 Bootstrap 4 垂直居中的更多信息

Now that Bootstrap 4 offers flexbox and other utilities, there are many approaches to vertical alignment. http://www.codeply.com/go/WG15ZWC4lf

现在 Bootstrap 4 提供了 flexbox 和其他实用程序,有很多垂直对齐的方法。http://www.codeply.com/go/WG15ZWC4lf

1 - Vertical Center Using Auto Margins:

1 - 使用自动边距的垂直中心:

Another way to vertically center is to use my-auto. This will center the element within it's container. For example, h-100makes the row full height, and my-autowill vertically center the col-sm-12column.

另一种垂直居中的方法是使用my-auto. 这将使元素在其容器内居中。例如,h-100使行全高,并使列my-auto垂直居中col-sm-12

<div class="row h-100">
    <div class="col-sm-12 my-auto">
        <div class="card card-block w-25">Card</div>
    </div>
</div>

Vertical Center Using Auto Margins Demo

使用自动边距演示的垂直居中

my-autorepresents margins on the vertical y-axis and is equivalent to:

my-auto表示垂直 y 轴上的边距,相当于:

margin-top: auto;
margin-bottom: auto;


2 - Vertical Center with Flexbox:

2 - 带有 Flexbox 的垂直中心:

vertical center grid columns

垂直中心网格列

Since Bootstrap 4 .rowis now display:flexyou can simply use align-self-centeron any column to vertically center it...

由于 Bootstrap 4.row现在是display:flex您可以简单地align-self-center在任何列上使用以将其垂直居中...

       <div class="row">
           <div class="col-6 align-self-center">
                <div class="card card-block">
                 Center
                </div>
           </div>
           <div class="col-6">
                <div class="card card-inverse card-danger">
                    Taller
                </div>
          </div>
    </div>

or, use align-items-centeron the entire .rowto vertically center align all col-*in the row...

或者,align-items-center在整个行中使用.row垂直居中对齐所有col-*...

       <div class="row align-items-center">
           <div class="col-6">
                <div class="card card-block">
                 Center
                </div>
           </div>
           <div class="col-6">
                <div class="card card-inverse card-danger">
                    Taller
                </div>
          </div>
    </div>

Vertical Center Different Height Columns Demo

垂直居中不同高度列演示

See this Q/A to center, but maintain equal height

看到这个 Q/A 居中,但保持相等的高度



3 - Vertical Center Using Display Utils:

3 - 使用 Display Utils 的垂直居中:

Bootstrap 4 has display utilsthat can be used for display:table, display:table-cell, display:inline, etc.. These can be used with the vertical alignment utilsto align inline, inline-block or table cell elements.

自举4具有显示utils的,可以被用于display:tabledisplay:table-celldisplay:inline等。这些可与所使用的垂直取向utils的要对齐的内联,内联块或表格单元格的元件。

<div class="row h-50">
    <div class="col-sm-12 h-100 d-table">
        <div class="card card-block d-table-cell align-middle">
            I am centered vertically
        </div>
    </div>
</div>

Vertical Center Using Display Utils Demo

使用 Display Utils演示的垂直居中

More examples
Vertical center image in <div>
Vertical center .row in .container
Vertical center and bottom in <div>
Vertical center child inside parent
Vertical center full screen jumbotron

更多示例
垂直中心的垂直中心图像<div>
.container 中的
垂直中心<div>.row垂直中心和底部在
父级内的垂直中心子项
垂直中心全屏超大屏幕



Important!Did I mention height?

重要的!我提到身高了吗?

Remember vertical centering is relative to the height of the parentelement. If you want to center on the entire page, in most cases, this should be your CSS...

记住垂直居中是相对于元素的高度。如果你想以整个页面为中心,在大多数情况下,这应该是你的 CSS ...

body,html {
  height: 100%;
}

Or use min-height: 100vh(min-vh-100in Bootstrap 4.1+) on the parent/container. If you want to center a child element inside the parent. The parent must have a defined height.

或者在父/容器上使用min-height: 100vhmin-vh-100在 Bootstrap 4.1+ 中)。如果要将子元素居中放置在父元素中。父级必须具有定义的高度

Also see:
Vertical alignment in bootstrap 4
Bootstrap 4 Center Vertical and Horizontal Alignment

另请参阅:
bootstrap 4 中的垂直对齐
Bootstrap 4 中心垂直和水平对齐

回答by Pete

you can vertically align your container by making the parent container flex and adding align-items:center:

您可以通过使父容器伸缩并添加align-items:center以下内容来垂直对齐容器:

body {
  display:flex;
  align-items:center;
}

Updated Pen

更新笔

回答by Manoj

Following bootstrap 4 classes helped me solve this

以下引导程序 4 类帮助我解决了这个问题

<div class="col text-center justify-content-center align-self-center">
    <img width=3rem src=".." alt="...">
</div>

回答by Greg Gum

Because none of the above worked for me, I am adding another answer.

因为以上都不适合我,所以我添加了另一个答案。

Goal: To vertically and horizontally align a div on a page using bootstrap 4 flexbox classes.

目标:使用 bootstrap 4 flexbox 类垂直和水平对齐页面上的 div。

Step 1: Set your outermost div to a height of 100vh. This sets the height to 100% of the Veiwport Height. If you don't do this, nothing else will work. Setting it to a height of 100%is only relative to the parent, so if the parent is not the full height of the viewport, nothing will work. In the example below, I set the Body to 100vh.

第 1 步:将最外面的 div 设置为100vh. 这会将高度设置为 Veiwport 高度的 100%。如果你不这样做,其他任何事情都不会奏效。将其设置100%为仅相对于父级的高度,因此如果父级不是视口的完整高度,则没有任何作用。在下面的示例中,我将 Body 设置为 100vh。

Step 2: Set the container div to be the flexbox container with the d-flexclass.

第二步:将容器div设置为带有d-flex类的flexbox容器。

Step 3: Center div horizontally with the justify-content-centerclass.

第 3 步:将 div 与justify-content-center班级水平居中。

Step 4: Center div vertically with the align-items-center

第 4 步:将 div 垂直居中 align-items-center

Step 5: Run page, view your vertically and horizontally centered div.

第 5 步:运行页面,查看垂直和水平居中的 div。

Note that there is no special class that needs to be set on the centered div itself (the child div)

请注意,在居中的 div 本身(子 div)上不需要设置特殊的类

<body style="background-color:#f2f2f2; height:100vh;">

<div class="h-100 d-flex justify-content-center align-items-center">
    <div style="height:600px; background-color:white; width:600px;">
</div>

</div>

</body>

回答by Nate Beers

.jumbotron {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

回答by AlexNikonov

I've tried all the answers herefrom, but found out here is the difference between h-100and vh-100Here is my solution:

我已经尝试了这里的所有答案,但发现这里是h-100vh-100之间的区别 这是我的解决方案:

      <div className='container vh-100 d-flex align-items-center col justify-content-center'>
        <div className="">
             ...
        </div>
      </div >

回答by Tariqul_Islam

<div class="col-lg-5 col-sm-5 offset-1 d-flex">
            <div class="offer-txt justify-content-center align-self-center">
                <span class="inner-title">Our Offer</span>
                <h2 class="section-title">Today's Special </h2>
                <p>One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly.</p>
            </div>
        </div>

enter image description here

在此处输入图片说明

回答by vallismortis

In Bootstrap 4 (beta), use align-middle. Refer to Bootstrap 4 Documentation on Vertical alignment:

在 Bootstrap 4(测试版)中,使用align-middle. 请参阅有关垂直对齐的 Bootstrap 4 文档

Change the alignment of elements with the vertical-alignmentutilities. Please note that vertical-align only affects inline, inline-block, inline-table, and table cellelements.

Choose from .align-baseline, .align-top, .align-middle, .align-bottom, .align-text-bottom, and .align-text-topas needed.

使用垂直对齐实用程序更改元素的对齐方式。请注意, vertical-align 仅影响inlineinline-blockinline-table表格单元格元素。

选择.align-baseline.align-top.align-middle.align-bottom.align-text-bottom,和.align-text-top需要。

回答by webjay

I did it this way with Bootstrap 4.3.1:

我用 Bootstrap 这样做了4.3.1

<div class="d-flex vh-100">
  <div class="d-flex w-100 justify-content-center align-self-center">
    I'm in the middle
  </div>
</div>

回答by Rob

<div class="row">
  <div class="col-md-6">
     <img src="/assets/images/ebook2.png" alt="" class="img-fluid">
  </div>
  <div class="col-md-6 my-auto">
     <h3>Heading</h3>
     <p>Some text.</p>
   </div>
</div>

This line is where the magic happens <div class="col-md-6 my-auto">, the my-autowill center the content of the column. This works great with situations like the code sample above where you might have a variable sized image and need to have the text in the column to the right line up with it.

这一行是魔法发生的地方<div class="col-md-6 my-auto">,它my-auto将使列的内容居中。这对于像上面的代码示例这样的情况非常有用,在这种情况下,您可能有一个可变大小的图像,并且需要将列中的文本与它对齐。