前端——CSS水平垂直居中的几种解决方案

水平垂直居中的几种解决方案

<div class="sup">
    <div class="sub"></div>
</div>
  • 利用CSS3的弹性盒子:(父元素display:flex;子元素margin:auto;)
.sup{
    width:400px;
    height:400px;
    background-color:#ccc;
    display:flex;
}
.sub{
    width:100px;
    height:100px;
    background-color:#000;
    margin:auto;
}
  • flex布局:(父元素display:flex;justify-content:center;align-items:center;)
.sup{
    width:400px;
    height:400px;
    background-color:#ccc;
    display:flex;
    justify-content:center;
    align-items:center;
}
.sub{
    width:100px;
    height:100px;
    background-color:#000;
}
  • position 搭配 margin
    父元素设置为:position: relative;
    子元素设置为:position: absolute;
    距上50%,据左50%,然后减去元素自身宽度的一半就可以实现
.sup{
    width:400px;
    height:400px;
    background-color:#ccc;
    position:relative;
}
.sub{
    width:100px;
    height:100px;
    background-color:#000;
    position:absolute;
    top:50%;
    left:50%;
    margin:-50px 0px 0px -50px;
}
  • position 搭配 transform
.sup{
    width:400px;
    height:400px;
    background-color:#ccc;
    position:relative;
}
.sub{
    width:100px;
    height:100px;
    background-color:#000;
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值