下载APP

垂直居中和水平居中

水平居中

一、行内元素

1.定义行内内容(例如文字)

text-align:center

二、块级元素

1.用margin完成自使用居中

.son {
    margin:0 auto;
}

2.使用定位

父元素:

    .father {
        position:relative;
    }

子元素:

    .son {
        position:absolute;
        left:0;
        right:0;
        margin:auto;
    }

3.使用flex,当父元素设置如下属性,那么子元素就会居中对齐

父元素:

    .father {
        diplay:flex;
        justify-content: center;//主轴方向居中对齐 默认主轴是横着的
    }

4.使用定位和transform实现水平居中

父组件:

.father {
    position:realative;
}

子组件:

    .son {
        position:absolute;
        left:50%;//整体向右移动父组件的50%
        transform: translate(-50%);//在向左移动自身的50%
    }

垂直居中

一、行内元素

1.定义行内内容(例如文字)

.son {
    line-height:10px;//这里的值是行的高度
}

二、块级元素

1.使用定位

父元素:

    .father {
        position:relative;
    }

子元素:

    .son {
        position:absolute;
        top:0;
        bottom:0;
        margin:auto;
    }

2.使用flex,当父元素设置如下属性,那么子元素就会居中对齐

父元素:

    .father {
        diplay:flex;
        align-item: center;//次轴方向居中对齐,默认主轴是横着的
    }

3.使用定位和transform实现水平居中

父组件:

.father {
    position:realative;
}

子组件:

    .son {
        position:absolute;
        top:50%;//整体向右移动父组件的50%
        transform: translate(0,-50%);//在向左移动自身的50%
    }

在线举报