从头开始——未知宽高元素水平垂直居中

很久没有记录平时学习的知识了,总感觉边看边遗忘。哈哈哈,还不是因为自己很懒。

未知宽高元素水平水平垂直居中方法总结如下:

1、弹性盒子flex: 在未知子元素,父元素宽高的情况下使用flex布局,一劳永逸

.parent {

    display: flex;

    justify-content: center;

    align-items: center;

}

2、伪元素:已知父元素宽高,子元素未知

.parent {

    width: 300px;

    height: 300px;

    text-align: center;

}

.parent ::before {

    content: '';

    display: inline-block;

    width: 0;

    height: 100%;

    vertical-align: middle;

}

.child {

    display:inline-block

}

3、定位+transform

.parent {

    height: 300px;

    width: 300px;

    position: relative;

     background: #ccc

}

.child {

    position: absolute;

    left: 50%;

    top: 50%;

    transform: translate(-50%, -50%)

}

4、显示为table

.parent {

    display: table;

    height: 300px;

    width: 300px;

    background-color: #eee

}

.child {

    display: table-cell;

    vertical-align: middle;

    background-color: #555;

}

如上四种是比较常见的写法。

猜你喜欢

转载自blog.csdn.net/weixin_33860147/article/details/90842447
今日推荐