简述水平垂直居中布局的3种方法

偶遇经典面试题,就思考了一下。

这个问题比较简单了,但是想通过各种角度来思考就不那么容易了。其实各种方法大同小异,一下举例说明。

基本结构:

<body>
    <div id="con">
        <div id="back" class="center">
        </div>
    </div>

</body>

1.利用绝对定位,设置top、left、margin属性。

#back {
   position: absolute;
   width: 300px;
   height: 300px;
   background-color: gray;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
}

2.利用绝对定位,设置top right bottom left属性。

#back {
   position: absolute;
   width: 300px;
   height: 300px;
   border: 1px solid red;
   top: 0;
   left: 0;
   bottom: 0;
   right: 0;
   margin: auto;
}

3.利用flex布局

#con {
   display: flex;
   justify-content: center;
   align-items: center;
   height: 800px;
}

#back {
   width: 300px;
   height: 300px;
   border: 1px solid purple;
}

其实,这些基本用法在工程项目中很少使用,都是依赖框架。但是,基本原理还是要知道的。其他方式自行探索吧。

吾生也有涯,而知也无涯。

猜你喜欢

转载自blog.csdn.net/vampire10086/article/details/108256147