CSS五种居中方法
1.方法一
通过写一个 标签,i标签的高度为百分之百,让i标签的中点和要居中元素的中点处在同一位置
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>五大居中1</title>
<style>
*{margin:0;padding:0;}
.box{width:500px;height:500px;margin:100px auto;border:1px solid #000;
text-align:center;
}
.box .zi{width:200px;height:200px;background:#9f9;
display:inline-block;vertical-align:middle;}
.box i{display:inline-block;height:100%;vertical-align:middle;}
</style>
</head>
<body>
<div class="box">
<div class="zi"></div><i></i>
</div>
</body>
</html>
2.方法二
使用定位方法,将需要居中的元素相对其父级定位,然后通过left:0;right:0;top:0;bottom:0;margin:auto;实现居中
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>五大居中2</title>
<style>
*{margin:0;padding:0;}
.box{width:500px;height:500px;margin:100px auto;border:1px solid #000;
text-align:center;position:relative;}
.box .zi{width:200px;height:200px;background:#9f9;
position:absolute;
left:0;right:0;top:0;bottom:0;margin:auto;
}
</style>
</head>
<body>
<div class="box">
<div class="zi"></div>
</div>
</body>
</html>
3.方法三
先使用定位,然后将左边的距离设为left:50%-元素自身的宽度/2
上边距设为top:50%-元素自身的高度/2
缺点:当元素大小改变时需要重新计算减去的高度或宽度
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>五大居中3</title>
<style>
*{margin:0;padding:0;}
.box{width:500px;height:500px;margin:100px auto;border:1px solid #000;
text-align:center;position:relative;}
.box .zi{width:200px;height:200px;background:#9f9;
position:absolute;
left:50%;top:50%;margin:-100px 0 0 -100px;
}
</style>
</head>
<body>
<div class="box">
<div class="zi"></div>
</div>
</body>
</html>
4.方法四
同样需要用到定位,将需要定位的元素设置为left:50%;top:50%;transform:translate(-50%,-50%);
translate(-50%,-50%) 作用是,往上(x轴),左(y轴)移动自身长宽的 50%,以使其居于中心位置
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>五大居中4</title>
<style>
*{margin:0;padding:0;}
.box{width:500px;height:500px;margin:100px auto;border:1px solid #000;
text-align:center;position:relative;}
.box .zi{width:200px;height:200px;background:#9f9;
position:absolute;
left:50%;top:50%;transform:translate(-50%,-50%);
}
</style>
</head>
<body>
<div class="box">
<div class="zi"></div>
</div>
</body>
</html>
5.方法五
这个用的是弹性盒中的方法,即display:flex;align-items:center(垂直居中);justify-content:center(水平居中);
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>五大居中5</title>
<style>
*{margin:0;padding:0;}
.box{width:500px;height:500px;margin:100px auto;border:1px solid #000;
text-align:center;display:flex;align-items:center;justify-content:center;}
.box .zi{width:200px;height:200px;background:#9f9;}
</style>
</head>
<body>
<div class="box">
<div class="zi"></div>
</div>
</body>
</html>