一、自适应的方式
<!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>水平垂直居中</title>
</head>
<style>
.parent{
height: 100px;
width: 200px;
border: 1px solid #333;
position: relative;
margin: 100px;
}
.parent .child{
height: 50px;
width: 80px;
background-color: rosybrown;
position: absolute;
margin: auto;
top: 0;
bottom: 0;
right: 0;
left: 0;
}
</style>
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>
</html>
效果展示
二、通过子元素的宽高设置
<!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>水平垂直居中</title>
</head>
<style>
.parent2{
margin: 100px;
height: 100px;
width: 200px;
border: 1px solid #333;
position: relative;
}
.parent2 .child{
height: 50px;
width: 100px;
background-color:aquamarine;
position: absolute;
left: 50%;
margin-left: -50px;
top: 50%;
margin-top: -25px;
}
</style>
<body>
<div class="parent2">
<div class="child"></div>
</div>
</body>
</html>
效果展示
三、伸缩盒
<!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>伸缩盒</title>
</head>
<style>
.parent{
width: 200px;
height: 100px;
margin: 100px;
border: 1px solid #333;
display: flex;
align-items: center;
justify-content: center;
}
.item{
width: 100px;
height: 50px;
background-color: burlywood;
text-align: center;
line-height: 50px;
</style>
<body>
<div class="parent">
<div class="item">伸缩盒</div>
</div>
</body>
</html>