前端常用居中方法

前端常用居中方式

整理了一些前端常用的居中方法,有错误的地方请大家多多指教。


水平居中

transform(css3)

.parent {
    position: relative;
}
.child {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
}

flex布局(css3)

.parent {
    display: flex;
    justify-content: center;
}

居中的元素为内联元素

.parent {
    text-align: center;
}

居中的元素为块级元素

方法一:设置margin

.child {
    margin: 0 auto;
}

方法二:元素修改为inline-block

.parent {
    text-align: center;
}
.child {
    display: inline-block;
}

居中元素为块级元素且知道宽度

方法一:

.child {
    position: relative;
    width:100px;
    left: 50%;
    margin-left: -50px;
}

方法二:

.parent {
    position: relative;
}
.child {
    position: absolute;
    width:100px;
    left: 50%;
    margin-left: -50px;
}

垂直居中

transform(css3)

.parent {
    position: relative;
}
.child {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}

flex布局(css3)

.parent {
    display: flex;
    align-items: center;
}

子元素为内联元素

.parent{
    line-height: 100px;
    height: 100px;
}

居中元素为块级元素且高度固定

方法一:

.parent {
    position: relative;
}
.child {
    height: 100px;
    position: absolute;
    top: 50%;
    margin-top: -50px;
}

方法二:

.child {
    position: relative;
    top: 50%;
    height: 100px;
    margin-top: -50px;
}
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值