<div>元素在页面中垂直和水平的最佳方法?
我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?
<div>元素在页面中垂直和水平的最佳方法?
我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?
当前回答
实际上有一个解决方案,使用css3,它可以垂直居中一个未知高度的div。诀窍是将div向下移动50%,然后使用transformmy将其移回中间。唯一的前提条件是要居中的元素有一个父元素。例子:
<div class="parent">
<div class="center-me">
Text, images, whatever suits you.
</div>
</div>
.parent {
/* height can be whatever you want, also auto if you want a child
div to be responsible for the sizing */
height: 200px;
}
.center-me {
position: relative;
top: 50%;
transform: translateY(-50%);
/* prefixes needed for cross-browser support */
-ms-transform: translateY(-50%);
-webkit-transform: translateY(-50%);
}
所有主流浏览器和ie9及以上版本都支持(别担心ie8,因为它在今年秋天和winxp一起死了。感谢上帝)。
JS小提琴演示
其他回答
div {
border-style: solid;
position: fixed;
width: 80%;
height: 80%;
left: 10%;
top: 10%;
}
调整左侧和顶部的宽度和高度,即(100% - 80%)/ 2 = 10%
下面是我之前写的一个脚本(它是用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();
};
在父元素上使用display:grid并将margin:auto设置为居中元素即可:
请看下面的片段:
html,身体{ 宽度:100%; 高度:100%; 保证金:0; 填充:0; } .container { 显示:网格; 高度:90%; 背景颜色:蓝色; } .content { 保证金:汽车; 颜色:白色; } < div class = "容器" > <div class="content"> cented div here</div> < / div >
我喜欢的方法是将一个盒子垂直和水平居中,是以下技术:
外容器
应有显示:表;
内容器
应该有display: table-cell; 应该有垂直对齐:中间; 应该有text-align: center;
内容框
应该有显示:inline-block; 应该重新调整水平文本对齐,如。text-align:左;或者text-align: right;,除非你想让文本居中
这种技术的优雅之处在于,你可以将你的内容添加到内容框中,而不用担心它的高度或宽度!
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>
看看这小提琴!
EDIT
是的,我知道你可以通过transform实现或多或少相同的灵活性:translate(-50%, -50%);或者transform: translate3d(-50%,-50%, 0);,我建议的技术有更好的浏览器支持。即使使用浏览器前缀,如-webkit, -ms或-moz, transform也不能提供完全相同的浏览器支持。
所以如果你关心旧的浏览器(例如。IE9及以下版本),您不应该使用transform进行定位。
我会使用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>