美文网首页
css水平、垂直居中的写法,请至少写出4种?

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

作者: Astep | 来源:发表于2022-01-11 11:41 被阅读0次

第一种利用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;
        }

相关文章

网友评论

      本文标题:css水平、垂直居中的写法,请至少写出4种?

      本文链接:https://www.haomeiwen.com/subject/ihybcrtx.html