Html 使用 margin:auto 垂直对齐一个 div

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

Using margin:auto to vertically-align a div

htmlcsscentering

提问by savinger

So I know we can center a div horizontally if we use margin:0 auto;. Should margin:auto auto;work how I think it should work? Centering it vertically as well?

所以我知道如果我们使用margin:0 auto;. 应该margin:auto auto;如何工作,我认为它应该如何工作?垂直居中?

Why doesn't vertical-align:middle;work either?

为什么也vertical-align:middle;不起作用?

.black {
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    background:rgba(0,0,0,.5);
}
.message {
    background:yellow;
    width:200px;
    margin:auto auto;
    padding:10px;
}
<div class="black">
    <div class="message">
        This is a popup message.
    </div>
</div>

JSFiddle

JSFiddle

回答by o.v.

You can't use:

你不能使用:

vertical-align:middlebecause it's notapplicable to block-level elements

vertical-align:middle因为它是不是适用于块级元素

margin-top:autoand margin-bottom:autobecause their used values would compute as zero

margin-top:auto并且margin-bottom:auto因为它们的使用值将计算为零

margin-top:-50%because percentage-based margin values are calculated relative to the widthof containing block

margin-top:-50%因为基于百分比的边距值是相对于包含块的宽度计算的

In fact, the nature of document flow and element height calculation algorithmsmake it impossible to use margins for centering an element vertically inside its parent. Whenever a vertical margin's value is changed, it will trigger a parent element height re-calculation (re-flow), which would in turn trigger a re-center of the original element... making it an infinite loop.

事实上,文档流的性质和元素高度计算算法使得无法使用边距将元素垂直居中于其父元素内。每当垂直边距的值发生变化时,它都会触发父元素高度重新计算(重新流动),这又会触发原始元素的重新居中......使其成为无限循环。

You can use:

您可以使用:

A few workarounds like thiswhich work for your scenario; the three elements have to be nested like so:

一些像这样的解决方法适用于您的场景;这三个元素必须像这样嵌套:

.container {
    display: table;
    height: 100%;
    position: absolute;
    overflow: hidden;
    width: 100%;
}
.helper {
    #position: absolute;
    #top: 50%;
    display: table-cell;
    vertical-align: middle;
}
.content {
    #position: relative;
    #top: -50%;
    margin: 0 auto;
    width: 200px;
    border: 1px solid orange;
}
<div class="container">
    <div class="helper">
        <div class="content">
            <p>stuff</p>
        </div>
    </div>
</div

JSFiddleworks fine according to Browsershot.

根据 Browsershot,JSFiddle工作正常。

回答by zpr

Since this question was asked in 2012 and we have come a long way with browser support for flexboxes, I felt as though this answer was obligatory.

由于这个问题是在 2012 年提出的,而且我们在浏览器对 flexbox 的支持方面取得了长足的进步,我觉得这个答案似乎是必须的。

If the display of your parent container is flex, then yes, margin: auto auto(also known as margin: auto) will work to center it both horizontally and vertically, regardless if it is an inlineor blockelement.

如果您的父容器的显示为flex,则yesmargin: auto auto(也称为margin: auto)将使其水平和垂直居中,无论它是否为inlineblock元素。

#parent {
    width: 50vw;
    height: 50vh;
    background-color: gray;
    display: flex;
}
#child {
    margin: auto auto;
}
<div id="parent">
    <div id="child">hello world</div>
</div>

Note that the width/height do not have to be specified absolutely, as in this example jfiddlewhich uses sizing relative to the viewport.

请注意,不必绝对指定宽度/高度,如本示例中的 jfiddle,它使用相对于视口的大小。

Although browser support for flexboxes is at an all-time high at time of posting, many browsers still do not support it or require vendor prefixes. Refer to http://caniuse.com/flexboxfor updated browser support information.

尽管在发布时浏览器对 flexbox 的支持处于历史最高水平,但许多浏览器仍然不支持它或需要供应商前缀。有关更新的浏览器支持信息,请参阅http://caniuse.com/flexbox

Update

更新

Since this answer received a bit of attention, I would also like to point out that you don't need to specify marginat all if you're using display: flexand would like to center all of the elements in the container:

由于这个答案受到了一些关注,我还想指出,margin如果您正在使用display: flex并希望将容器中的所有元素居中,则根本不需要指定:

#parent {
    width: 50vw;
    height: 50vh;
    background-color: gray;
    display: flex;
    align-items: center; /* horizontal */
    justify-content: center; /* vertical */
}
<div id="parent">
    <div>hello world</div>
</div>

回答by shshaw

Here's the best solution I've found: http://jsfiddle.net/yWnZ2/446/Works in Chrome, Firefox, Safari, IE8-11 & Edge.

这是我找到的最佳解决方案:http: //jsfiddle.net/yWnZ2/446/适用于 Chrome、Firefox、Safari、IE8-11 和 Edge。

If you have a declared height(height: 1em, height: 50%, etc.) or it's an element where the browser knows the height (img, svg, or canvasfor example), then all you need for vertical centering is this:

如果你有一个声明的height( height: 1em, height: 50%, 等等) 或者它是一个浏览器知道高度的元素 ( img, svg, 或者canvas例如),那么你需要的垂直居中是这样的:

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

You'll usually want to specify a widthor max-widthso the content doesn't stretch the whole length of the screen/container.

您通常会希望指定widthmax-width使内容不拉伸屏幕/容器的整个长度。

If you're using this for a modal that you want always centered in the viewport overlapping other content, use position: fixed;for both elements instead of position: absolute. http://jsfiddle.net/yWnZ2/445/

如果您将它用于希望始终在与其他内容重叠的视口中居中的模式,请使用position: fixed;两个元素而不是position: absolute. http://jsfiddle.net/yWnZ2/445/

Here's a more complete writeup: http://codepen.io/shshaw/pen/gEiDt

这是一个更完整的文章:http: //codepen.io/shshaw/pen/gEiDt

回答by Gal Margalit

Edit: it's 2020, I would use flex box instead.

编辑:现在是 2020 年,我会改用 flex box。

Original answer:

原答案:

Html

html

<body>
  <div class="centered">
  </div>
</body>

CSS

CSS

.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

回答by Paula Fleck

I know the question is from 2012, but I found the easiest way ever, and I wanted to share.

我知道问题来自 2012 年,但我找到了有史以来最简单的方法,我想分享一下。

HTML:

HTML:

<div id="parent">
     <div id="child">Content here</div>
</div>

and CSS:

和 CSS:

#parent{
     height: 100%;
     display: table;
}    
#child {
     display: table-cell;
     vertical-align: middle; 
}

回答by tuff

If you know the height of the div you want to center, you can position it absolutely within its parent and then set the topvalue to 50%. That will put the top of the child div 50% of the way down its parent, i.e. too low. Pull it back up by setting its margin-topto half its height. So now you have the vertical midpoint of the child div sitting at the vertical midpoint of the parent - vertically centered!

如果您知道要居中的 div 的高度,则可以将其绝对定位在其父级内,然后将该top值设置为50%. 这将使子 div 的顶部低于其父级的 50%,即太低。通过将其设置margin-top为一半高度将其拉回。所以现在你有子 div 的垂直中点坐在父级的垂直中点 - 垂直居中!

Example:

例子:

.black {
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    background:rgba(0,0,0,.5);
}
.message {
    background:yellow;
    width:200px;
    margin:auto auto;
    padding:10px;
    position: absolute;
    top: 50%;
    margin-top: -25px;
    height: 50px;
}
<div class="black">
    <div class="message">
        This is a popup message.
    </div>
</div>

http://jsfiddle.net/yWnZ2/2/

http://jsfiddle.net/yWnZ2/2/

回答by DevWL

Those two solution require only two nested elements.
First- Relative and absolute positioning if the content is static(manual center).

这两个解决方案只需要两个嵌套元素。
First-如果内容是静态的(手动居中),相对和绝对定位。

.black {
    position:relative;
    min-height:500px;
    background:rgba(0,0,0,.5);

}
.message {
    position:absolute;
    margin: 0 auto;
    width: 180px;
    top: 45%; bottom:45%;  left: 0%; right: 0%;
}

https://jsfiddle.net/GlupiJas/5mv3j171/

https://jsfiddle.net/GlupiJas/5mv3j171/

or for fluid design- for exact content center use below example instead:

用于流体设计- 对于确切的内容中心,请使用以下示例:

.message {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

https://jsfiddle.net/GlupiJas/w3jnjuv0/

https://jsfiddle.net/GlupiJas/w3jnjuv0/

You need 'min-height' set in case the content will exceed 50% of window height. You can also manipulate this height with media query for mobile and tablet devices . But only if You play with responsive design.

您需要设置 'min-height',以防内容超过窗口高度的 50%。您还可以使用针对移动设备和平板设备的媒体查询来操作此高度。但前提是你玩响应式设计。

I guess You could go further and use simple JavaScript/JQuery script to manipulate the min-height or fixed height if there is a need for some reason.

我想如果出于某种原因需要,您可以更进一步并使用简单的 JavaScript/JQuery 脚本来操作最小高度或固定高度。

Second- if content is fluidu can also use table and table-cell css properties with vertical alignment and text-align centered:

其次-如果内容是流动的,你还可以使用垂直对齐和文本对齐居中的表格和表格单元格 css 属性:

/*in a wrapper*/  
display:table;   

and

/*in the element inside the wrapper*/
display:table-cell;
vertical-align: middle;
text-align: center;

Works and scale perfectly, often used as responsive web design solution with grid layouts and media query that manipulate the width of the object.

完美地工作和缩放,通常用作响应式网页设计解决方案,具有操作对象宽度的网格布局和媒体查询。

.black {
    display:table;
    height:500px;
    width:100%;
    background:rgba(0,0,0,.5);

}
.message {
    display:table-cell;
    vertical-align: middle;
    text-align: center;
}

https://jsfiddle.net/GlupiJas/4daf2v36/

https://jsfiddle.net/GlupiJas/4daf2v36/

I prefer table solution for exact content centering, but in some cases relative absolute positioning will do better job especially if we don't want to keep exact proportion of content alignment.

我更喜欢精确内容居中的表格解决方案,但在某些情况下,相对绝对定位会做得更好,特别是如果我们不想保持内容对齐的精确比例。

回答by Seetpal singh

.black {
    display:flex;
    flex-direction: column;
    height: 200px;
    background:grey
}
.message {
    background:yellow;
    width:200px;
    padding:10px;
    margin: auto auto;
}
<div class="black">
    <div class="message">
        This is a popup message.
    </div>
</div>

回答by Sudipto Chakraborty

.black {
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    background:rgba(0,0,0,.5);
}
.message {
    position: absolute;
    top:50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background:yellow;
    width:200px;
    padding:10px;
}

 - 


----------


<div class="black">
<div class="message">
    This is a popup message.
</div>

回答by DanielBlazquez

Using Flexbox:

使用弹性盒:

HTML:

HTML:

<div class="container">
  <img src="http://lorempixel.com/400/200" />
</div>

CSS:

CSS:

.container {
  height: 500px;
  display: flex;
  justify-content: center; /* horizontal center */
  align-items: center;     /* vertical center */
}

View result

查看结果