CSS 中水平垂直居中的几种方法
1.使用定位流
原理:盒子先向下偏移父元素高度的50%,再向上偏移盒子高度的50%。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
html,
body {
100%;
height: 100%;
}
div {
300px;
height: 300px;
background: orange;
margin: 0 auto;
position: relative;
top: 50%;
margin-top: -150px;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
2.使用transform优化
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
html,
body {
100%;
height: 100%;
}
div {
300px;
height: 300px;
background: orange;
margin: 0 auto;
position: relative;
top: 50%;
/* margin-top: -150px; */
transform: translateY(-50%);
}
</style>
</head>
<body>
<div></div>
</body>
</html>
3.使用display: flex;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
html,
body {
100%;
height: 100%;
display: flex;
/* 水平居中 */
align-items: center;
/* 垂直居中 */
justify-content: center;
}
div {
300px;
height: 300px;
background: orange;
}
</style>
</head>
<body>
<div></div>
</body>
</html>