<div>元素在页面中垂直和水平的最佳方法?

我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?


当前回答

最好和最灵活的方式

这个演示的主要技巧是,在元素从上到下的正常流中,因此margin-top: auto被设置为零。然而,绝对定位元素对于自由空间的分布具有相同的作用,并且类似地可以在指定的顶部和底部垂直居中(在IE7中不起作用)。

这个技巧适用于任何大小的div。

div { 宽度:100 px; 身高:100 px; 背景颜色:红色; 位置:绝对的; 上图:0; 底部:0; 左:0; 右:0; 保证金:汽车; } < div > < / div >

其他回答

请使用以下CSS属性水平和垂直居中对齐元素。这对我来说很有效。

div {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0px;
  margin: auto;
  width: 100px;
  height: 100px;
}

是浏览器支持的,使用翻译功能强大。

position: absolute;
background-color: red;

width: 70%;     
height: 30%; 

/* The translate % is relative to the size of the div and not the container*/ 
/* 21.42% = ( (100%-70%/2) / 0.7 ) */
/* 116.666% = ( (100%-30%/2) / 0.3 ) */
transform: translate3d( 21.42%, 116.666%, 0);

尽管当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或其他答案中显示的固定宽度/高度解决方案。

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%的宽度和高度。

另一个答案是这样的。

<div id="container"> 
    <div id="centered"> </div>
</div>

还有css:

#container {
    height: 400px;
    width: 400px;
    background-color: lightblue;
    text-align: center;
}

#container:before {
    height: 100%;
    content: '';
    display: inline-block;
    vertical-align: middle;
}

#centered {
    width: 100px;
    height: 100px;
    background-color: blue;
    display: inline-block;
    vertical-align: middle;
    margin: 0 auto;
}