五种居中方法

五种居中方法

一、第一种是将块元素的两个子元素都设置成inline-block行内块元素,一个元素高度等于父元素的高度,使得两个元素基点相互居中。最后再把等于父元素高度的子元素隐藏起来,另外一个子元素就水平垂直居中了。

<style>
.box{width:500px;height:500px;box-shadow:0 0 5px #000;text-align:center;font-size:0;}
.zi{width:160px;height:100px;background:#0f0;display:inline-block;vertical-align:middle;}
.box:after{content:"";display:inline-block;height:100%;background:#f00;vertical-align:middle;}
</style>
</head>
<body>
<div class="box">
	<div class="zi"></div>
</div>

二、第二种是使用定位和margin:auto来做到水平垂直居中

<style>
.box{width:500px;height:500px;box-shadow:0 0 5px #000;position:relative;}
.zi{width:160px;height:100px;background:#0f0;position:absolute;left:0;right:0;top:0;bottom:0;margin:auto;}
</style>
</head>
<body>
<div class="box">
	<div class="zi"></div>
</div>
</body>

三、第三种是直接使用弹性盒子水平垂直居中。

<style>
.box{width:500px;height:500px;box-shadow:0 0 5px #000;display:flex;justify-content:center;align-items:center;}
.zi{width:160px;height:100px;background:#0f0;}
</style>
</head>
<body>
<div class="box">
 <div class="zi"></div>
</div>
</body>

四、第四种也是使用定位,先让子元素的左上角位于父元素的正中心,然后根据子元素的宽高用margin调整位置。

<style>
.box{width:500px;height:500px;box-shadow:0 0 5px #000;position:relative;}
.zi{width:160px;height:100px;background:#0f0;position:absolute;left:50%;top:50%;margin:-50px 0 0 -80px;}
</style>
</head>
<body>
<div class="box">
 <div class="zi"></div>
</div>
</body>

五、第五种也是用定位,先让子元素的左上角位于父元素的正中心,再使用transform:translate(-50%,-50%)子元素水平垂直居中,这种办法相较于上一种不用考虑子元素的宽高。

<style>
.box{width:500px;height:500px;box-shadow:0 0 5px #000;position:relative;}
.zi{width:160px;height:100px;background:#0f0;position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);}
</style>
</head>
<body>
<div class="box">
 <div class="zi"></div>
</div>
</body>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值