您当前的位置: 首页 >  css

彭世瑜

暂无认证

  • 3浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

css:整理9种元素水平垂直居中的方法

彭世瑜 发布时间:2021-11-28 10:23:08 ,浏览量:3

实现效果 在这里插入图片描述

容器基础样式

/* 容器基础样式 */
.box-wrap {
    width: 400px;
    height: 400px;
    border: 1px solid #eeeeee;
    margin-top: 20px;
}

.box {
    width: 200px;
    height: 200px;
    background-color: green;
    /* 文字居中 */
    text-align: center;
    color: #ffffff;
    line-height: 200px;
}

1、flex

.box-wrap {
    display: flex;
    justify-content: center;
    align-items: center;
}

2、table-cell

.box-wrap {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}

.box{
    display: inline-block;
}

3、margin+transform

.box {
    margin: 50% auto;
    transform: translateY(-50%);
}

4、inline-block + vertical-align(没有测试通过)

.box-wrap{
    /*使行内元素或者行内块级元素水平居中*/
    text-align: center;
}

.box {
    display: inline-block;
    vertical-align: middle;
}

5、absolute + margin

.box-wrap {
    position: relative;
}

.box {
    position: absolute;
    left: 50%;
    top: 50%;
    /*  盒子高度的一半 */
    margin-left: -100px;
    margin-top: -100px;
}

6、absolute + margin-auto

.box-wrap {
    position: relative;
}

.box {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

7、absolute + transform

.box-wrap {
    position: relative;
}


.box {
    position: absolute;
    left: 50%;
    top: 50%;
    /*  移动自身的50% */
    transform: translate(-50%, -50%);
}

8、grid + self

.box-wrap {
    display: grid;
}

.box {
    align-self: center;
    justify-self: center;
}

9、grid + items

.box-wrap {
    display: grid;
    place-items: center;
}
关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.0480s