<div>元素在页面中垂直和水平的最佳方法?
我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?
<div>元素在页面中垂直和水平的最佳方法?
我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?
当前回答
最好和最灵活的方式
这个演示的主要技巧是,在元素从上到下的正常流中,因此margin-top: auto被设置为零。然而,绝对定位元素对于自由空间的分布具有相同的作用,并且类似地可以在指定的顶部和底部垂直居中(在IE7中不起作用)。
这个技巧适用于任何大小的div。
div { 宽度:100 px; 身高:100 px; 背景颜色:红色; 位置:绝对的; 上图:0; 底部:0; 左:0; 右:0; 保证金:汽车; } < div > < / div >
其他回答
解决方案
仅使用两行CSS,利用Flexbox的神奇力量
.parent { display: flex; }
.child { margin: auto }
抱歉回复晚了 最好的办法是
div {
position: fixed;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -100px;
}
上边距和左边距应该根据你的div框大小
尽管当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或其他答案中显示的固定宽度/高度解决方案。
我认为有两种方法使div中心对齐通过CSS。
.middleDiv {
position : absolute;
width : 200px;
height : 200px;
left : 50%;
top : 50%;
margin-left : -100px; /* half of the width */
margin-top : -100px; /* half of the height */
}
这是最简单最好的方法。演示请访问以下链接:
http://w3webpro.blogspot.in/2013/07/how-to-make-div-horizontally-and.html
我知道我迟到了,但是这里有一种方法可以将一个维度未知的div集中在一个维度未知的父元素中。
风格:
<style>
.table {
display: table;
height: 100%;
margin: 0 auto;
}
.table-cell {
display: table-cell;
vertical-align: middle;
}
.centered {
background-color: red;
}
</style>
HTML:
<div class="table">
<div class="table-cell"><div class="centered">centered</div></div>
</div>
演示:
看看这个演示。