Html 在页面上垂直和水平居中 <div> 的最佳方法?

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

Best way to center a <div> on a page vertically and horizontally?

htmlcssalignmentvertical-alignmentcentering

提问by Vladimir Starkov

Best way to center a <div>element on a page both vertically and horizontally?

<div>在页面上垂直和水平居中元素的最佳方法?

I know that margin-left: auto; margin-right: auto;will center on the horizontal, but what is the best way to do it vertically, too?

我知道这margin-left: auto; margin-right: auto;将以水平方向为中心,但是垂直方向的最佳方法是什么?

回答by Vladimir Starkov

The best and most flexible way

最好最灵活的方式

My demo on dabblet.com

在 dabblet.com 上的演示

The main trick in this demo is that in the normal flow of elements going from top to bottom, so the margin-top: autois set to zero. However, an absolutely positioned element acts the same for distribution of free space, and similarly can be centered vertically at the specified topand bottom(does not work in IE7).

这个演示的主要技巧是在元素从上到下的正常流动中,所以margin-top: auto设置为零。然而,一个绝对定位的元素对于自由空间的分布是一样的,同样可以在指定的top和垂直居中bottom(在 IE7 中不起作用)。

This trick will work with any sizes of div.

这个技巧适用于任何大小的div.

div {
 width: 100px;
 height: 100px;
 background-color: red;
 
 position: absolute;
 top:0;
 bottom: 0;
 left: 0;
 right: 0;
   
 margin: auto;
}
<div></div>

回答by tombul

Even though this did not work when the OP asked this question, I think, for modern browsers at least, the best solution is to use display: flexor pseudo classes.

尽管这在 OP 提出这个问题时不起作用,但我认为,至少对于现代浏览器,最好的解决方案是使用display: flex伪类

You can see an example in the following fiddle. Here is the updated fiddle.

您可以在以下小提琴中看到一个示例。这是更新的小提琴

For pseudo classesan example could be:

对于伪类,一个例子可能是:

.centerPseudo {
    display:inline-block;
    text-align:center;
}

.centerPseudo::before{
    content:'';
    display:inline-block;
    height:100%;
    vertical-align:middle;
    width:0px;
}

The usage of display: flex, according to css-tricksand MDNis as follows:

display: flex的用法,根据css-tricksMDN如下:

.centerFlex {
  align-items: center;
  display: flex;
  justify-content: center;
}

There are other attributes available for flex, which are explained in above mentioned links, with further examples.

还有其他可用于 flex 的属性,在上面提到的链接中进行了解释,并提供了更多示例。

If you have to support older browsers, which don't support css3, then you should probably use javascript or the fixed width/height solution shown in the other answers.

如果您必须支持不支持 css3 的旧浏览器,那么您可能应该使用 javascript 或其他答案中显示的固定宽度/高度解决方案。

回答by robjez

Simplicity of this technique is stunning:
(This method has its implications though, but if you only need to center element regardless of flow of the rest of the content, it's just fine. Use with care)

这种技术的简单性令人惊叹:(
尽管这种方法有其含义,但如果您只需要将元素居中而不管其余内容的流动如何,那就没问题了。小心使用)

Markup:

标记:

<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum accumsan tellus purus, et mollis nulla consectetur ac. Quisque id elit at diam convallis venenatis eget sed justo. Nunc egestas enim mauris, sit amet tempor risus ultricies in. Sed dignissim magna erat, vel laoreet tortor bibendum vitae. Ut porttitor tincidunt est imperdiet vestibulum. Vivamus id nibh tellus. Integer massa orci, gravida non imperdiet sed, consectetur ac quam. Nunc dignissim felis id tortor tincidunt, a eleifend nulla molestie. Phasellus eleifend leo purus, vel facilisis massa dignissim vitae. Pellentesque libero sapien, tincidunt ut lorem non, porta accumsan risus. Morbi tempus pharetra ex, vel luctus turpis tempus eu. Integer vitae sagittis massa, id gravida erat. Maecenas sed purus et magna tincidunt faucibus nec eget erat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc nec mollis sem.</div>

And CSS:

和 CSS:

div {
  color: white;
  background: red;
  padding: 15px;
  position: absolute;
  top: 50%;
  left: 50%;
  -ms-transform: translateX(-50%) translateY(-50%);
  -webkit-transform: translate(-50%,-50%);
  transform: translate(-50%,-50%);
}   

This will center element horizontally and vertically too. No negative margins, just power of transforms. Also we should already forget about IE8 shouldn't we?

这也将水平和垂直居中元素。没有负边距,只有转换的力量。此外,我们应该已经忘记了 IE8 不是吗?

回答by MDTech.us_MAN

I would use translate:

我会用translate

First position the div's top left corner at the center of the page (using position: fixed; top: 50%; left: 50%). Then, translatemoves it up by 50% of the div's height to center it vertically on the page. Finally, translate also moves the div to the right by 50% of it's width to center it horizontally.

首先将 div 的左上角定位在页面中央(使用position: fixed; top: 50%; left: 50%)。然后,translate将其向上移动 div 高度的 50%,使其在页面上垂直居中。最后, translate 还将 div 向右移动其宽度的 50% 以使其水平居中。

I actually think that this method is better than many of the others, since it does not require any changes on the parent element.

我实际上认为这种方法比许多其他方法要好,因为它不需要对父元素进行任何更改。

translateis better than translate3din some scenarios due to it being supported by a greater number of browsers. http://caniuse.com/#search=translate

translatetranslate3d在某些情况下更好,因为它被更多的浏览器支持。http://caniuse.com/#search=translate

To sum it up, this method is supported on all versions of Chrome, Firefox 3.5+, Opera 11.5+, all versions of Safari, IE 9+, and Edge.

综上所述,该方法在所有版本的 Chrome、Firefox 3.5+、Opera 11.5+、所有版本的 Safari、IE 9+ 和 Edge 上都支持。

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  
  font-size: 20px;
  background-color: cyan;
  border: darkgreen 5px solid;
  padding: 5px;
  z-index: 100;
}

table {
    position: absolute;
    top: 0;
    left: 0;
}

td {
    position: relative;
    top: 0;
    left: 0;
}
<table>
<tr>
    <td>
        <div class="centered">This div<br />is centered</div>
        <p>
            Lorem ipsum dolor sit amet, nam sint laoreet at, his ne sumo causae, simul decore deterruisset ne mel. Exerci atomorum est ut. At choro vituperatoribus usu. Dico epicurei persequeris quo ex, ea ius zril phaedrum eloquentiam, duo in aperiam admodum fuisset. No quidam consequuntur usu, in amet hinc simul eos. Ex soleat meliore percipitur mea, nihil omittam salutandi ut eos. Mea et impedit facilisi pertinax, ea viris graeci fierent pri, te sonet intellegebat his. Vis denique albucius instructior ad, ex eum iudicabit elaboraret. Sit ea intellegam liberavisse. Nusquam quaestio maiestatis ut qui, eam decore altera te. Unum cibo aliquip ut qui, te mea doming prompta. Ex rebum interesset nam, te nam zril suscipit, qui suavitate explicari appellantur te. Usu brute corpora mandamus eu. Dicit soluta his eu. In sint consequat sed, quo ea tota petentium. Adhuc prompta splendide mel ad, soluta delenit nec cu.
        </p>
    </td>
    <td>
        <p>
            Lorem ipsum dolor sit amet, dico choro recteque te cum, ex omnesque consectetuer sed, alii esse utinam et has. An qualisque democritum usu. Ea has habeo labores, laoreet intellegat te mea. Eius equidem inermis vel ne. Ne eum sonet labitur, nec id natum munere. Primis graecis est cu, quis dictas eu mea, eu quem offendit forensibus nec. Id animal mandamus his, vis in sonet tempor luptatum. Ne civibus oporteat comprehensam vix, per facete discere atomorum eu. Mucius probatus volutpat sit an, sumo nominavi democritum eam ut. Ea sit choro graece debitis, per ex verear voluptua epicurei. Id eum wisi dicat, ea sit velit doming cotidieque, eu sea amet delenit. Populo tacimates dissentiunt has cu. Has wisi hendrerit at, et quo doming putent docendi. Ea nibh vide omnium usu.
        </p>
    </td>
</tr>
</table>

Notice, however, that this method makes this div stay in one place while the page is being scrolled. This may be what you want but if not, there is another method.

但是请注意,此方法使该 div 在页面滚动时停留在一个位置。这可能是您想要的,但如果不是,还有另一种方法。



Now, if we try the same CSS, but with position set to absolute, it will be in the center of the last parent that has an absolute position.

现在,如果我们尝试相同的 CSS,但将位置设置为绝对,它将位于具有绝对位置的最后一个父级的中心。

.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);

  font-size: 20px;
  background-color: cyan;
  border: darkgreen 5px solid;
  padding: 5px;
  z-index: 100;
}

table {
    position: absolute;
    top: 0;
    left: 0;
}

td {
    position: relative;
    top: 0;
    left: 0;
}
<table>
<tr>
    <td>
        <div class="centered">This div<br />is centered</div>
        <p>
            Lorem ipsum dolor sit amet, nam sint laoreet at, his ne sumo causae, simul decore deterruisset ne mel. Exerci atomorum est ut. At choro vituperatoribus usu. Dico epicurei persequeris quo ex, ea ius zril phaedrum eloquentiam, duo in aperiam admodum fuisset. No quidam consequuntur usu, in amet hinc simul eos. Ex soleat meliore percipitur mea, nihil omittam salutandi ut eos. Mea et impedit facilisi pertinax, ea viris graeci fierent pri, te sonet intellegebat his. Vis denique albucius instructior ad, ex eum iudicabit elaboraret. Sit ea intellegam liberavisse. Nusquam quaestio maiestatis ut qui, eam decore altera te. Unum cibo aliquip ut qui, te mea doming prompta. Ex rebum interesset nam, te nam zril suscipit, qui suavitate explicari appellantur te. Usu brute corpora mandamus eu. Dicit soluta his eu. In sint consequat sed, quo ea tota petentium. Adhuc prompta splendide mel ad, soluta delenit nec cu.
        </p>
    </td>
    <td>
        <p>
            Lorem ipsum dolor sit amet, dico choro recteque te cum, ex omnesque consectetuer sed, alii esse utinam et has. An qualisque democritum usu. Ea has habeo labores, laoreet intellegat te mea. Eius equidem inermis vel ne. Ne eum sonet labitur, nec id natum munere. Primis graecis est cu, quis dictas eu mea, eu quem offendit forensibus nec. Id animal mandamus his, vis in sonet tempor luptatum. Ne civibus oporteat comprehensam vix, per facete discere atomorum eu. Mucius probatus volutpat sit an, sumo nominavi democritum eam ut. Ea sit choro graece debitis, per ex verear voluptua epicurei. Id eum wisi dicat, ea sit velit doming cotidieque, eu sea amet delenit. Populo tacimates dissentiunt has cu. Has wisi hendrerit at, et quo doming putent docendi. Ea nibh vide omnium usu.
        </p>
    </td>
</tr>
</table>

回答by user2555501

I think there are two ways to make a div center align through CSS.

我认为有两种方法可以通过 CSS 使 div 中心对齐。

.middleDiv {
    position : absolute;    
    width    : 200px;
    height   : 200px;
    left     : 50%;
    top      : 50%;
    margin-left : -100px; /* half of the width  */
    margin-top  : -100px; /* half of the height */
}

This is the simple and best way. for the demo please visit below link:

这是最简单和最好的方法。有关演示,请访问以下链接:

http://w3webpro.blogspot.in/2013/07/how-to-make-div-horizontally-and.html

http://w3webpro.blogspot.in/2013/07/how-to-make-div-horizo​​ntally-and.html

回答by Ulad Kasach

Simple solution taking advantage of Flex Display

利用 Flex Display 的简单解决方案

 <div style = 'display:flex; position:absolute; top:0; bottom:0; right:0; left:0; '>
      <div id = 'div_you_want_centered' style = 'margin:auto;'> 
           This will be Centered 
      </div>
 </div>

Check out http://css-tricks.com/snippets/css/a-guide-to-flexbox/

查看http://css-tricks.com/snippets/css/a-guide-to-flexbox/

The first div takes up the whole screen and has a display:flex set for every browser. The second div (centered div) takes advantage of the display:flex div where margin:auto works brilliantly.

第一个 div 占据整个屏幕,并为每个浏览器设置了一个 display:flex 。第二个 div(居中 div)利用了 display:flex div,其中 margin:auto 工作得非常出色。

NoteIE11+ compatibility. (IE10 w/ prefix).

注意IE11+ 兼容性。(IE10 带前缀)。

回答by Kop4lyf

If you are looking at the new browsers(IE10+),

如果您正在查看新的浏览器(IE10+),

then you can make use of transform property to align a div at the center.

然后你可以利用 transform 属性在中心对齐一个 div。

<div class="center-block">this is any div</div>

And css for this should be:

而为此的 css 应该是:

.center-block {
  top:50%;
  left: 50%;
  transform: translate3d(-50%,-50%, 0);
  position: absolute;
}

The catch here is that you don't even have to specify the height and width of the div as it takes care by itself.

这里的问题是您甚至不必指定 div 的高度和宽度,因为它会自行处理。

Also, if you want to position a div at the center of another div, then you can just specify the position of outer div as relativeand then this CSS starts working for your div.

此外,如果您想将一个 div 定位在另一个 div 的中心,那么您可以将外部 div 的位置指定为相对位置,然后此 CSS 开始为您的 div 工作。

How it works:

这个怎么运作:

When you specify left and top at 50%, the div goes at the the bottom right quarter of the page with its top-left end pinned at the center of the page. This is because, the left/top properties(when given in %) are calculated based on height of the outer div(in your case, window).

当您将 left 和 top 指定为 50% 时,div 位于页面右下四分之一处,其左上端固定在页面中央。这是因为,左侧/顶部属性(以 % 给出时)是根据外部 div(在您的情况下,窗口)的高度计算的。

But transform uses height/width of the element to determine translation, so you div will move left(50% width) and top(50% its height) since they are given in negatives, thus aligning it to the center of the page.

但是变换使用元素的高度/宽度来确定平移,因此您的 div 将向左移动(宽度的 50%)和顶部(高度的 50%),因为它们以负数形式给出,从而将其与页面的中心对齐。

If you have to support older browsers(and sorry including IE9 as well) then the table cell is most popular method to use.

如果您必须支持较旧的浏览器(很抱歉也包括 IE9),那么表格单元格是最常用的方法。

回答by John Slegers

My prefered way to center a box both vertically and horizontally, is the following technique :

我首选的垂直和水平居中方法是以下技术:

The outer container

外容器

  • should have display: table;
  • 应该有 display: table;

The inner container

内部容器

  • should have display: table-cell;
  • should have vertical-align: middle;
  • should have text-align: center;
  • 应该有 display: table-cell;
  • 应该有 vertical-align: middle;
  • 应该有 text-align: center;

The content box

内容框

  • should have display: inline-block;
  • should re-adjust the horizontal text-alignment to eg. text-align: left;or text-align: right;, unless you want text to be centered
  • 应该有 display: inline-block;
  • 应该将水平文本对齐重新调整为例如。text-align: left;或者text-align: right;,除非您希望文本居中

The elegance of this technique, is that you can add your content to the content box without worrying about its height or width!

这种技术的优雅之处在于,您可以将内容添加到内容框而无需担心其高度或宽度!

Demo

演示

body {
    margin : 0;
}

.outer-container {
    position : absolute;
    display: table;
    width: 100%; /* This could be ANY width */
    height: 100%; /* This could be ANY height */
    background: #ccc;
}

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

.centered-content {
    display: inline-block;
    text-align: left;
    background: #fff;
    padding : 20px;
    border : 1px solid #000;
}
<div class="outer-container">
   <div class="inner-container">
     <div class="centered-content">
        You can put anything here!
     </div>
   </div>
</div>

See also this Fiddle!

另见这个小提琴



EDIT

编辑

Yes, I know you can achieve more or less the same flexibility with transform: translate(-50%, -50%);or transform: translate3d(-50%,-50%, 0);, the technique I'm proposing has far better browser support. Even with browsers prefixes like -webkit, -msor -moz, transformdoesn't offer quite the same browser support.

是的,我知道您可以使用transform: translate(-50%, -50%);或实现或多或少相同的灵活性,transform: translate3d(-50%,-50%, 0);我提出的技术具有更好的浏览器支持。即使浏览器前缀喜欢-webkit-ms或者-moztransform不提供完全一样的浏览器支持。

So if you care about older browsers (eg. IE9 and below), you should not use transformfor positioning.

因此,如果您关心旧浏览器(例如 IE9 及以下),则不应使用transform定位。

回答by AmazingTurtle

position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);

Explanation:

解释:

Give it an absolute positioning (the parent should have relative positioning). Then, the upper left corner is moved to the center. Because you don't know the width/height yet, you use css transform to translate the position relatively to the middle. translate(-50%, -50%) does reduce the x and y position of the upper left corner by 50% of width and height.

给它一个绝对定位(父级应该有相对定位)。然后,左上角移动到中心。因为您还不知道宽度/高度,所以您使用 css 变换将位置相对于中间平移。translate(-50%, -50%) 确实将左上角的 x 和 y 位置减少了宽度和高度的 50%。

回答by Andreas Grech

Here is a script i wrote a while back (it is written using the jQuery library):

这是我不久前写的一个脚本(它是使用 jQuery 库编写的

var centerIt = function (el /* (jQuery element) Element to center */) {
    if (!el) {
        return;
    }
    var moveIt = function () {
        var winWidth = $(window).width();
        var winHeight = $(window).height();
        el.css("position","absolute").css("left", ((winWidth / 2) - (el.width() / 2)) + "px").css("top", ((winHeight / 2) - (el.height() / 2)) + "px");
    }; 
    $(window).resize(moveIt);
    moveIt();
};