1.给父元素设置flex布局;
<style>
.parent {
width: 200px;
height: 200px;
background-color: green;
display: flex;
justify-content: center;
align-items: center;
}
.son {
width: 100px;
height: 100px;
background-color: pink;
}
</style>
</head>
<body>
<div class="parent">
<div class="son"></div>
</div>
</body>
2. 已知盒子的宽高
<style>
.parent {
width: 200px;
height: 200px;
background-color: green;
position: relative;
}
.son {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
</style>
</head>
<body>
<div class="parent">
<div class="son"></div>
</div>
</body>
3.元素的宽高未知
<style>
.parent {
width: 200px;
height: 200px;
background-color: green;
position: relative;
}
.son {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="parent">
<div class="son"></div>
</div>
</body>
4.position:子绝父相 top:0;right:0;bottom:0;left:0; margin:auto
.son {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
5.设置文本的居中
<style>
.parent {
width: 200px;
height: 200px;
background-color: green;
}
p {
color: pink;
text-align: center;
line-height: 200px;
}
</style>
</head>
<body>
<div class="parent">
<p>我是仙女</p>
</div>