1.利用定位(Position)
<!doctype html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
*{
margin:0;
padding:0;
}
.parent{
width:500px;
height:500px;
background: red;
position: relative;
}
.child{
width:50px;
height:50px;
background: yellow;
position:absolute;
left:50%;
top:50%;
margin-top:-25px;
margin-left:-25px;
}
</style>
</head>
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>
</html
2.定位(position)与位移(translate)
//html
<div class="parent">
<div class="child">
</div>
</div>
//css
.parent{
width:300px;
height:300px;
background-color: red;
position: relative;
}
.child{
width:100px;
height:100px;
background-color: pink;
position:absolute;
left:50%;
top:50%;
transform: translate(-50%,-50%);
}
3.定位
//HTML
<div class="one">
<div class="two">
</div>
</div>
//css
.one{
width:400px;
height:400px;
background-color: red;
position: relative;
}
.two{
width:100px;
height:100px;
background-color: pink;
position: absolute;
margin:auto;
left:0;
top:0;
bottom:0;
right:0;
}
4.flex弹性布局
//html
<div class="parent">
<div class="child">
</div>
</div>
//css
.parent{
display: flex;
justify-content: center;
align-items: center;
width:300px;
height:300px;
background-color: red;
}
.child{
width:100px;
height:100px;
background-color: pink;
}