css水平垂直居中

方法一:position定位(适用于子盒子有宽度和高度的时候)

方法二:子元素绝对定位,距离顶部 50%,左边50%,然后使用css3 transform:translate(-50%; -50%)(子盒子有或没有宽高的时候都适用)

方法三:flex布局(子盒子有或没有宽高的时候都适用)

 

方法一的代码如下:

            .div1 {
                width: 600px;
                height: 600px;
                background: red;
                position: absolute;
                left: 50%;
                top: 50%;
                margin-left: -300px;
                margin-top: -300px;
            }

 

图片展示:

 

方法二的代码如下:

            .div1 {
                position: absolute;
                left: 50%;
                top: 50%;
                transform: translate(-50%, -50%);
            }

 

方法三的代码如下: 

.div1 {
    height:800px;
    -webkit-display:flex;
    display:flex;
    -webkit-align-items:center;
    align-items:center;
    -webkit-justify-content:center;
    justify-content:center;
    border:1px solid #ccc;
}
.div1 div {
    width:600px;
    height:600px;
    background-color:red;
}

 

posted @ 2022-03-23 23:23  紫色云  阅读(34)  评论(0)    收藏  举报