盒子垂直水平居中
一、无父盒子情况
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=https://juejin.cn/post/6909698127689220109, initial-scale=1.0">
<title>Document</title>
<style>
*{
padding: 0;
margin: 0;
}
div{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
width: 200px;
height: 200px;
background-color: blueviolet;
}
</style>
</head>
<body>
<div>123</div>
</body>
</html>
二、有父盒子情况
1、position+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>
*{
padding: 0;
margin: 0;
}
.father{
position: relative;
width: 200px;
height: 200px;
background-color: yellow;
}
.son{
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
width: 100px;
height: 100px;
background-color: blueviolet;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
2、position+margin
<!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>
*{
padding: 0;
margin: 0;
}
.father{
position: relative;
width: 200px;
height: 200px;
background-color: yellow;
}
.son{
position: absolute;
top:50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
width: 100px;
height: 100px;
background-color: blueviolet;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
3、flex布局
<!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>
*{
padding: 0;
margin: 0;
}
.father{
width: 200px;
height: 200px;
background-color: yellow;
display: flex;
align-items: center;
justify-content: center;
}
.son{
width: 100px;
height: 100px;
background-color: blueviolet;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
4、表格布局
<!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>
*{
padding: 0;
margin: 0;
}
.father{
display: table-cell;
text-align: center;
vertical-align: middle;
width: 200px;
height: 200px;
background-color: yellow;
}
.son{
display: inline-block;
width: 100px;
height: 100px;
background-color: blueviolet;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>