如何让一个div水平垂直居中

在工作中 经常会碰到让一个div框针对某个模块水平垂直居中 针对这种情况 有多种方法 现在一一实现一下

一. div绝对定位水平垂直居中 margin 负间距

代码:

.box {
    width: 200px;
    height: 200px;
    background: yellow;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -100px;
    margin-top: -100px;
}

效果如下:
在这里插入图片描述

二. div绝对定位水平垂直居中 transforms变形

代码:

.box {
    width: 200px;
    height: 200px;
    background: greenyellow;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
}

效果如下:

在这里插入图片描述

三. 弹性盒模型 css不定宽高水平垂直居中

代码:

.par{
    display: flex;
    justify-content: center;
    align-items: center;
    height: 768px; // 去掉父元素高度时只能水平居中
}
.par .child{
    background: blueviolet;
    width: 200px;
    height: 200px;
}

效果如下:
在这里插入图片描述

四. table-cell 是不支持设置 width: 100%; 想让 .parent 和 其容器宽度一致最好设置一个 dispaly: table; 父容器

代码:

div.parent-box {
    display: table;
    width: 100%;
}

div.parent {
    display: table-cell;
    height: 200px;
    width: 200px;
    background-color: orange;
    text-align: center;
    vertical-align: middle;
}

div.child {
    display: inline-block;
    width: 100px;
    height: 100px;
    background-color: blue;
}

效果如下:
在这里插入图片描述

五. 绝对定位 calc()函数动态计算实现水平垂直居中

代码:

.par {
    position: relative;
    width: 500px;
    height: 500px;
    border: 1px solid saddlebrown;
}

.child {
    position: absolute;
    width: 200px;
    height: 200px;
    left: -webkit-calc((500px - 200px)/2);
    top: -webkit-calc((500px - 200px)/2);
    left: -moz-calc((500px - 200px)/2);
    top: -moz-calc((500px - 200px)/2);
    left: calc((500px - 200px)/2);
    top: calc((500px - 200px)/2);
    background: gold;
}

需要注意父子元素
效果如下:

在这里插入图片描述

六. div绝对定位水平垂直居中 margin auto 实现绝对定位元素的居中

代码:

.box {
    width: 200px;
    height: 200px;
    background: lightcoral;
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    margin: auto;
}

效果如下:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值