【问题标题】:How to center div in the page? (Height & Width)?如何使页面中的 div 居中? (高度宽度)?
【发布时间】:2011-10-11 23:49:00
【问题描述】:

愚蠢的问题,但我无法找到答案,因为所有答案都假设 div 在宽度方面居中。

我需要的是使 div 以高度和宽度居中,因此位于页面的非常中心。

我试过这个,但它只是以页面宽度而不是高度来居中 div。

#myDiv {
   width: 500px;
   height: 500px;
   margin: auto;
}

那么我怎样才能把它放在页面的中心呢? )))

【问题讨论】:

标签: css html position


【解决方案1】:

#myDiv 元素周围创建一个ID 为wrapper 的包装器,并应用此CSS 代码:

#wrapper{
    display: table;
}
#myDiv{
    display: table-cell;
    vertical-align: middle; /*Vertically centered*/
    text-align: center; /* Horizontally centered */
}

此代码居中任意宽度/高度的元素。

【讨论】:

    【解决方案2】:
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -250px; /*(half of width)*/
    margin-top: -250px;  /*(half of height)*/
    

    应该可以的。

    【讨论】:

    • 首先到达那里,是的,这应该可以。如果宽度/高度是自动的,请寻找 js 替代方案。还必须注意,父 div 应该有一个position:relative
    猜你喜欢
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    相关资源
    最近更新 更多