css水平、垂直居中的写法,请至少写出4种?

第一种利用flex布局实现

.div1 {
            width: 200px;
            height: 200px;
            border: 1px solid #333;
            display: flex;
            align-items: center;
            justify-content: center;
        }

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

第二种用定位和转换实现

.div2 {
            width: 200px;
            height: 200px;
            border: 1px solid #333;
            position: relative;
        }

        .div2 div {
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
        }

第三种用表格布局实现

.div3 {
            width: 200px;
            height: 200px;
            border: 1px solid #333;
            display: table-cell;
            text-align: center;
            vertical-align: middle;
        }

        .div3 div {
            width: 100px;
            height: 100px;
            background-color: red;
            display: inline-block;
        }

第四种用定位和外边距auto实现

.div4 {
            width: 200px;
            height: 200px;
            border: 1px solid #333;
            position: relative;
        }

        .div4 div {
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
            margin: auto;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
        }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容