CSS元素水平垂直居中的几种方法

一、使用弹性布局

align-items: center;设置flex子项在垂直方向上居中;justify-content: center;设置flex子项在水平方向上居中。

<div class="box1">
    <div class="box2"></div>
</div>
.box1 {
    width:  600px;
    height: 600px;
    border: 2px solid yellowgreen;
    /* 使用弹性布局实现子元素居中 */
    display: flex;
    align-items: center;
    justify-content: center;
}
.box2 {
    width: 500px;
    height: 500px;
    border: 2px solid red;
}

二、使用绝对定位配合偏移

设置子元素绝对定位:top: 50%;left:50%后,可以看见界面上子元素左上角位于父元素的中心点上;此时需要偏移设置:transform: translate(-50%, -50%),此处的-50%是以子元素的中心点作为对其点的,实现的效果是元素在X轴方向上左移自身宽度的50%,在Y轴方向上上移自身高度的50%,从而达到真实的水平垂直居中效果。

<div class="box2">
    <div class="box3"></div>
</div>
.box2 {
    width: 500px;
    height: 500px;
    border: 2px solid red;
    position: relative;
}
.box3 {
    width: 400px;
    height: 400px;
    border: 2px solid blue;
    /* 绝对定位配合偏移实现居中 */
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

 

三、使用绝对定位配合外边距

<div class="box2">
    <div class="box4"></div>
</div>
.box2 {
    width: 500px;
    height: 500px;
    border: 2px solid red;
}
.box4 {
    width: 300px;
    height: 300px;
    border: 2px solid yellow;
    /*将四个定位属性的值都设置为0实现水平垂直居中 */
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    margin: auto;
}

四、使用网格布局

<div class="box4">
    <div class="box5"></div>
</div>
.box4 {
    width: 300px;
    height: 300px;
    border: 2px solid yellow;
    /*使用网格布局实现内部元素居中 */
    display: grid;
    align-items: center;
    justify-content: center;
}
.box5 {
    width: 200px;
    height: 200px;
    border: 2px solid green;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值