小编典典

在页面上垂直和水平居中放置<div>的最佳方法?

php

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

我知道这margin-left: auto; margin-right: auto;将以水平为中心,但是垂直进行的最佳方法是什么?


阅读 603

收藏
2020-05-13

共1个答案

小编典典

该演示的主要技巧是元素的正常流动是从上到下,因此将margin-top: auto其设置为零。然而,绝对定位的元件作用为自由空间分布是相同的,并且类似地可以垂直在指定为中心top并且bottom(不IE7工作)。

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

div {
    width: 100px;
    height: 100px;
    background-color: red;

    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;

    margin: auto;
}
<div></div>
2020-05-13