1.定位加外间距
<style>
.box{
width: 300px;
height: 300px;
margin: 20px auto;
border: 1px solid black;
position: relative;
}
.box1{
width: 100px;
height: 100px;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
background-color: red;
}
</style>
</head>
<body>
<div class="box">
<aiv class="box1"></aiv>
</div>
</body>
效果图都一样就不重复展示:
2.定位加外间距负值
<style>
.box{
width: 300px;
height: 300px;
margin: 20px auto;
border: 1px solid black;
position: relative;
}
.box1{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin: -50px 0 0 -50px;
background-color: red;
}
</style>
</head>
<body>
<div class="box">
<aiv class="box1"></aiv>
</div>
</body>
3.弹性盒子
<style>
.box{
width: 300px;
height: 300px;
margin: 20px auto;
border: 1px solid black;
display: flex;justify-content: center;
align-items: center;
}
.box1{
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div class="box">
<aiv class="box1"></aiv>
</div>
</body>
4.定位和2d平移
<style>
.box{
width: 300px;
height: 300px;
margin: 20px auto;
border: 1px solid black;
position: relative;
}
.box1{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background-color: red;
}
</style>
</head>
<body>
<div class="box">
<aiv class="box1"></aiv>
</div>
</body>