css实现水平垂直居中的方式

本文探讨了四种常见的网页布局技术:绝对定位配合transform:translate(-50%,-50%)实现居中,margin: auto实现自适应,flexbox实现弹性布局,以及表格布局的垂直居中。通过实例对比,揭示了不同定位策略在实际开发中的应用场景和优势。
摘要由CSDN通过智能技术生成

1.绝对定位+ transform: translate(-50%, -50%);

.parent {
    height: 500px;
    position: relative;
}
.child {
    position: absolute;
    left: 50%;
    top: 50%;
    /* 相对于元素的自身宽高进行平移 */
    transform: translate(-50%, -50%);
}

2.绝对定位+margin:auto

.parent {
    height: 500px;
    position: relative;
}
.child{
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    margin: auto;
}

3.利用弹性布局 display:flex

.parent{
	height:500px;
	width:600px:
	display: flex;
    align-items: center;
    justify-content: center;
}
.child{
    height:300px;
	width:300px:
}

4.使用表格布局

.parent{
    height: 500px;
    width: 400px;
    background-color: green;
    display: table-cell;
    vertical-align: middle;
}
.child{
    height: 200px;
    width: 200px;
    background-color: red;
    margin: auto;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值