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

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


当前回答

最好和最灵活的方式

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

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

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

其他回答

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

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);

在父元素上使用display:grid并将margin:auto设置为居中元素即可:

请看下面的片段:

html,身体{ 宽度:100%; 高度:100%; 保证金:0; 填充:0; } .container { 显示:网格; 高度:90%; 背景颜色:蓝色; } .content { 保证金:汽车; 颜色:白色; } < div class = "容器" > <div class="content"> cented div here</div> < / div >

div {
    border-style: solid;
    position: fixed;
    width: 80%;
    height: 80%;
    left: 10%;
    top: 10%;
}

调整左侧和顶部的宽度和高度,即(100% - 80%)/ 2 = 10%

我认为有两种方法使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 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;
}