<body>
<div class="parent">
<div class="child">我是孩子</div>
</div>
</body>
1.首先是定位和浮动都不需要的
<style>
.parent {
width: 300px;
height: 300px;
background-color: pink;
border: 1px solid #000000;
}
.child {
width: 100px;
height: 100px;
background-color: hotpink;
margin-left: calc(50% - 50px);
margin-top: calc(50% - 50px);
}
</style>
这里一定要给父盒子加边框,否则父盒子会跟子盒子一起移动
2.基于定位(子绝父相),这里有三种方法实现
<style>
.parent {
position:relative
width: 300px;
height: 300px;
background-color: pink;
}
.child {
position:absolute;
width: 100px;
height: 100px;
background-color: hotpink;
margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
</style>
<style>
.parent {
position:relative
width: 300px;
height: 300px;
background-color: pink;
}
.child {
position:absolute;
width: 100px;
height: 100px;
background-color: hotpink;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}
</style>
<style>
.parent {
position:relative
width: 300px;
height: 300px;
background-color: pink;
}
.child {
position:absolute;
width: 100px;
height: 100px;
background-color: hotpink;
left: 50%;
top: 50%;
transform: translate(-50px,-50px);
}
</style>
3.基于浮动
<style>
.parent {
width: 300px;
height: 300px;
background-color: pink;
}
.child {
float:left;
width: 100px;
height: 100px;
background-color: hotpink;
float: left;
margin-left: calc(50% - 50px);
margin-top: calc(50% - 50px);
}
</style>
4.基于flex布局(这种简单,也最常用)
<style>
.parent {
display:flex;
width: 300px;
height: 300px;
background-color: pink;
justify-content: center;
align-items: center;
}
.child {
width: 100px;
height: 100px;
background-color: hotpink;
}
</style>
5.基于table-cell
这种方法有个缺陷,就是它的父亲必须要有固定宽和高,不能是百分比
<style>
.parent {
display: table-cell;
width: 300px;
height: 300px;
background-color: pink;
vertical-align: middle;
text-align: center;
}
.child {
display: inline-block;
width: 100px;
height: 100px;
background-color: hotpink;
}
</style>
以下是显现结果: