<div>元素在页面中垂直和水平的最佳方法?
我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?
<div>元素在页面中垂直和水平的最佳方法?
我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?
当前回答
我喜欢的方法是将一个盒子垂直和水平居中,是以下技术:
外容器
应有显示:表;
内容器
应该有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进行定位。
其他回答
I'm surprised this has not been mentioned yet, but the simplest way to do this would be by setting the height, margin (and width, if you want) using viewport sizes. As you might know, total height of the viewport = 100vh. Say you want the height of you container to occupy 60% (60vh) of the screen, you can divide the rest (40vh) equally between the top and the bottom margin so that the element aligns itself in the centre automatically. Setting the margin-left and margin-right to auto, will make sure the container is centred horizontally.
.container { 宽度:60大众;/ *可选* / 高度:60 vh; 利润率:20vh auto; 背景:# 333; } < div class = "容器" > < / div >
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 >
在父元素上使用display:grid并将margin:auto设置为居中元素即可:
请看下面的片段:
html,身体{ 宽度:100%; 高度:100%; 保证金:0; 填充:0; } .container { 显示:网格; 高度:90%; 背景颜色:蓝色; } .content { 保证金:汽车; 颜色:白色; } < div class = "容器" > <div class="content"> cented div here</div> < / div >
这个解决方案对我很有效
.middleDiv{
position : absolute;
height : 90%;
bottom: 5%;
}
(或高度:70% /底部:15%
高度:40% /底部:30%…)
解决方案
仅使用两行CSS,利用Flexbox的神奇力量
.parent { display: flex; }
.child { margin: auto }