水平垂直居中布局的多种实现方式

下面为公共代码:

<div class="box">
    <div class="small">small</div>
</div>
复制代码
.box {
    width: 300px;
    height: 300px;
    background: #ddd;
}
.small {
    background: red;
}
复制代码

水平垂直居中-->>absolute + margin实现

absolute + margin 第1种
.box {
    position: relative;
}
.small {
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -50px 0 0 -50px;
    width: 100px;
    height: 100px;
}
复制代码

Open in CodePen

absolute + margin 第2种
.box {
    position: relative;
}
.small {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
    width: 100px;
    height: 100px;
}
复制代码

Open in CodePen

水平垂直居中-->>absolute + calc 实现

.box {
    position: relative;
}
.small {
    position: absolute;
    top: calc(50% - 50px);
    left: calc(50% - 50px);
    width: 100px;
    height: 100px;
}
复制代码

Open in CodePen

水平垂直居中-->>absolute + transform 实现

.box {
    position: relative;
}
.small {
    position: absolute;
    top: 50%;
    left: 50%;
    /* transform: translate(-50%,-50%); */
    transform: translate3d(-50%,-50%,0);
    width: 100px;
    height: 100px;
}
复制代码

Open in CodePen

水平垂直居中-->>转行内元素

.box {
    line-height: 300px;
    text-align: center;
    font-size: 0px;
}
.small {
    padding: 6px 10px;
    font-size: 16px;
    display: inline-block;
    vertical-align: middle;
    line-height: 16px;
}
复制代码

Open in CodePen

水平垂直居中-->>table-cell

.box {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.small {
    padding: 6px 10px;
    display: inline-block;
}
复制代码

Open in CodePen

水平垂直居中-->>flex

flex 第1种
.box {
    display: flex;
    justify-content: center;
    align-items: center;
}
复制代码

Open in CodePen

flex 第2种
.box {
    display: flex;
    justify-content: center;
}
.small {
    align-self: center;
}
复制代码

Open in CodePen

水平垂直居中-->>grid

grid 第1种
.box {
    display: grid;
    justify-items: center;
    align-items: center;
}
复制代码

Open in CodePen

grid 第2种
.box {
    display: grid;
}
.small {
    justify-self: center;
    align-self: center;
}
复制代码

Open in CodePen

grid 第3种
.box {
    display: grid;
    justify-items: center;
}
.small {
    align-self: center;
}
复制代码

Open in CodePen

grid 第4种
.box {
    display: grid;
    align-items: center;
}
.small {
    justify-self: center;
}
复制代码

Open in CodePen

转载于:https://juejin.im/post/5c9f007bf265da30a857bb63

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值