<div>元素在页面中垂直和水平的最佳方法?
我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?
<div>元素在页面中垂直和水平的最佳方法?
我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?
当前回答
这个解决方案对我很有效
.middleDiv{
position : absolute;
height : 90%;
bottom: 5%;
}
(或高度:70% /底部:15%
高度:40% /底部:30%…)
其他回答
抱歉回复晚了 最好的办法是
div {
position: fixed;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -100px;
}
上边距和左边距应该根据你的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进行定位。
解决方案
仅使用两行CSS,利用Flexbox的神奇力量
.parent { display: flex; }
.child { margin: auto }
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 >
div {
border-style: solid;
position: fixed;
width: 80%;
height: 80%;
left: 10%;
top: 10%;
}
调整左侧和顶部的宽度和高度,即(100% - 80%)/ 2 = 10%