<div>元素在页面中垂直和水平的最佳方法?
我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?
<div>元素在页面中垂直和水平的最佳方法?
我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?
当前回答
这个解决方案对我很有效
.middleDiv{
position : absolute;
height : 90%;
bottom: 5%;
}
(或高度:70% /底部:15%
高度:40% /底部:30%…)
其他回答
利用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)。
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
解释:
给它一个绝对定位(父元素应该有相对定位)。然后,左上角被移动到中心。因为你还不知道宽度/高度,所以你使用css transform来转换相对于中间的位置。平移(-50%,-50%)会将左上角的x和y位置降低50%的宽度和高度。
请使用以下CSS属性水平和垂直居中对齐元素。这对我来说很有效。
div {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0px;
margin: auto;
width: 100px;
height: 100px;
}
尽管当OP问这个问题时,这并没有起作用,但我认为,至少对于现代浏览器来说,最好的解决方案是使用display: flex或伪类。
你可以在下面的小提琴中看到一个例子。 这是更新后的小提琴。
对于伪类,一个例子可以是:
.centerPseudo {
display:inline-block;
text-align:center;
}
.centerPseudo::before{
content:'';
display:inline-block;
height:100%;
vertical-align:middle;
width:0px;
}
display: flex的用法,根据css-tricks和MDN说明如下:
.centerFlex {
align-items: center;
display: flex;
justify-content: center;
}
flex还有其他可用的属性,在上面提到的链接中解释了这些属性,并提供了进一步的示例。
如果你必须支持不支持css3的旧浏览器,那么你可能应该使用javascript或其他答案中显示的固定宽度/高度解决方案。
这里还有一个方法(防弹),利用“display:table”规则:
标记
<div class="container">
<div class="outer">
<div class="inner">
<div class="centered">
...
</div>
</div>
</div>
</div>
CSS:
.outer {
display: table;
width: 100%;
height: 100%;
}
.inner {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered {
position: relative;
display: inline-block;
width: 50%;
padding: 1em;
background: orange;
color: white;
}