Html 如何使用 Bootstrap 垂直和水平居中块?

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

How I can center a block vertically and horizontally with Bootstrap?

htmlcsstwitter-bootstrap

提问by Julika

I have this form:

我有这个表格:

<div class="container-fluid">
<div class="span5 well">
<h2>Authentification</h2>
<form method="POST">...</form>
</div>
</div>

How I can center that block (div span5 well) vertically and horizontally? Thank you.

我如何垂直和水平居中该块(div span5 井)?谢谢你。

回答by Wex

Horizontal centering can be done by adding margin: 0 autoto an element that has no siblings.

水平居中可以通过添加margin: 0 auto到没有兄弟元素的元素来完成。

回答by Zulkhaery Basrul

<style>
.well
{       
    position:absolute;      
    width:200px;    
    height:200px;
    top: 50%;
    left: 50%;
    margin-top:-100px; /* negative number 1/2 height */
    margin-left:-100px; /* negative number 1/2 width */
    outline:1px solid #CCC;
}
</style>

<div class="container-fluid">
<div class="span5 well">
<h2>Authentification</h2>
<form method="POST">...</form>
</div>
</div>

回答by Tony

There's nothing conflicting with Bootstrap to use some JS for this, such as this guy's JQuery.vAlign plugin. I find that more straight-forward than the vertical-align tricks.

为此使用一些 JS 与 Bootstrap 没有任何冲突,例如这家伙的 JQuery.vAlign 插件。我发现这比垂直对齐技巧更直接。

回答by Sammy

Horizontal centering was mentioned earlier to set margin 0 auto.

前面提到了水平居中来设置边距 0 自动。

To vertically align the element dynamically (when you don't know the height) you can relatively shift it 50% (up or down) and then use transform: translateY(50%) (+/-) to center it within its parent container:

要动态垂直对齐元素(当您不知道高度时),您可以将其相对移动 50%(向上或向下),然后使用 transform: translateY(50%) (+/-) 将其在其父容器中居中:

div.span5 {
    margin: 0 auto;
    top:50%;
    width:400px;
    position:relative;
    transform: translateY(-50%);
}

fiddle

小提琴