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

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


当前回答

2018年使用CSS网格的方式:

.parent{
    display: grid;
    place-items: center center;
}

检查浏览器的支持,Caniuse建议它适用于Chrome 57、FF 52、Opera 44、Safari 10.1和Edge 16。我没有检查自己。

请看下面的片段:

.parent { 显示:网格; 放置物品:中心中心; /*place-items是align-items和justification -items的简写*/ 身高:200 px; 边框:1px纯黑色; 背景:gainsboro; } .child { 背景:白色; } < div class = "父" > < div class = "孩子" >为中心!< / div > < / div >

其他回答

下面是我之前写的一个脚本(它是用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();
};

这项技术的简单性令人惊叹: (尽管这个方法有它的含义,但是如果您只需要将元素居中,而不考虑其余内容的流,那么它是可以的。小心使用)

标记:

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

和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%);
}   

这将使元素水平和垂直居中。没有负边距,只有变换的幂。我们也应该忘记IE8,不是吗?

如果你正在研究新的浏览器(IE10+),

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

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

这个的css应该是:

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

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

同样,如果你想把一个div放在另一个div的中心,那么你可以指定外部div的相对位置,然后这个CSS开始为你的div工作。

工作原理:

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

但是transform使用元素的高度/宽度来决定转换,因此div将向左移动(50%宽度)和向上移动(50%高度),因为它们是以负号给出的,因此将其对齐到页面的中心。

如果你必须支持旧的浏览器(抱歉,包括IE9),那么表格单元格是最流行的方法。

div {
    border-style: solid;
    position: fixed;
    width: 80%;
    height: 80%;
    left: 10%;
    top: 10%;
}

调整左侧和顶部的宽度和高度,即(100% - 80%)/ 2 = 10%

我会使用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>