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

我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?


当前回答

我会使用translate:

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

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

在某些情况下,Translate比translate3d更好,因为它被更多的浏览器支持。https://caniuse.com/#feat=transforms2d

综上所述,所有版本的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>

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


现在,如果我们尝试相同的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>

其他回答

如果你正在使用JQuery,你可以使用.position();

<div class="positionthis"></div>

CSS

.positionthis {
    width:100px;
    height:100px;
    position: absolute;
    background:blue;
}

Javascript JQuery ()

$(document).ready(function () {
    $('.positionthis').position({
        of: $(document),
        my: 'center center',
        at: 'center center',
        collision: 'flip flip'
    });
});

http://jsfiddle.net/vx9gV/

另一个答案是这样的。

<div id="container"> 
    <div id="centered"> </div>
</div>

还有css:

#container {
    height: 400px;
    width: 400px;
    background-color: lightblue;
    text-align: center;
}

#container:before {
    height: 100%;
    content: '';
    display: inline-block;
    vertical-align: middle;
}

#centered {
    width: 100px;
    height: 100px;
    background-color: blue;
    display: inline-block;
    vertical-align: middle;
    margin: 0 auto;
}

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

.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 */
}

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

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

利用Flex显示的简单解决方案

 <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>

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

第一个div占据了整个屏幕,并有一个针对每种浏览器的显示:flex集。第二个div(居中div)充分利用了显示:flex div,其中margin:auto工作出色。

注意兼容IE11+。(IE10 w/ prefix)。

最好和最灵活的方式

这个演示的主要技巧是,在元素从上到下的正常流中,因此margin-top: auto被设置为零。然而,绝对定位元素对于自由空间的分布具有相同的作用,并且类似地可以在指定的顶部和底部垂直居中(在IE7中不起作用)。

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

div { 宽度:100 px; 身高:100 px; 背景颜色:红色; 位置:绝对的; 上图:0; 底部:0; 左:0; 右:0; 保证金:汽车; } < div > < / div >