绝对定位居中法有三种,还有一种是flex属性居中
1.绝对定位居中法
(利用绝对定位)(如果是在父盒子里居中,则个父盒子设置相对定位)子绝父相
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
margin: auto;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* 绝对定位垂直水平居中的方法 */
.box {
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
margin: auto;
width: 400px;
height: 300px;
background-color: aquamarine;
}
</style>
</head>
<body>
<div class="box">
</div>
</body>
</html>
2.绝对定位居中法
先让子盒子向右移动到父盒子长度的百分之五十,然后向左移动自身的一半
即是left:50%; margin-left为负数
然后向下移动父盒子高度的一半,在向上移动自身的一半
即是top50%;margin-top为负数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* 第二种绝对定位垂直水平居中的方法 */
.box {
position: absolute;
left: 50%;
margin-left: -200px;
top: 50%;
margin-top: -150px;
width: 400px;
height: 300px;
background-color: aquamarine;
}
</style>
</head>
<body>
<div class="box">
</div>
</body>
</html>
3.绝对定位垂直水平居中法
和第二种很像(有兼容性问题I6-I7-I8浏览器不支持)
先让子盒子向右移动到父盒子长度的百分之五十,
即是left:50%;
然后向下移动父盒子高度的一半,
即是top50%;
然后向左移动自身的一半、在向上移动自身的一半。使用transform属性
transform: translate(-50%,-50%);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* 第三种绝对定位垂直水平居中的方法 */
.box {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
/* 存在兼容性问题 I6-I7-I8浏览器不支持 */
width: 400px;
height: 300px;
background-color: aquamarine;
}
</style>
</head>
<body>
<div class="box">
</div>
</body>
</html>
4.flex属性居中法
首先给父盒子或者body设置flex属性
然后垂直居中align-items: center;
水平居中justify-content: center;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>flex属性居中法</title>
<style>
/* 第4种绝对定位垂直水平居中的方法 */
html,body{
/* 给body设置网页高度 */
height: 100%;
}
body{
display: flex;
/* 垂直方向居中 */
align-items: center;
/* 水平方向居中 */
justify-content: center;
}
.box {
width: 400px;
height: 300px;
background-color: aquamarine;
}
</style>
</head>
<body>
<div class="box">
</div>
</body>
</html>