五种居中方法
一、第一种是将块元素的两个子元素都设置成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>