html
<body>
<div class="main">
<div class="box"></div>
</div>
</body>
- 绝对定位加
margin: auto;
:
css
<style>
* {
padding: 0;
margin: 0;
}
.main {
width: 400px;
height: 400px;
border: 2px solid #000;
position: relative;
margin: 30px auto;
}
.box {
width: 100px;
height: 100px;
background-color: #f00;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
- 绝对定位加负 margin:
css
<style>
* {
padding: 0;
margin: 0;
}
.main {
width: 400px;
height: 400px;
border: 2px solid #000;
position: relative;
margin: 30px auto;
}
.box {
width: 100px;
height: 100px;
background-color: #f00;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
</style>
- margin 推动:
css
<style>
* {
padding: 0;
margin: 0;
}
.main {
width: 400px;
height: 400px;
border: 2px solid #000;
margin: 30px auto;
}
.box {
width: 100px;
height: 100px;
background-color: #f00;
margin: 150px 150px;
}
</style>
- flex 居中:
css
<style>
* {
padding: 0;
margin: 0;
}
.main {
width: 400px;
height: 400px;
border: 2px solid #000;
margin: 30px auto;
display: flex;
justify-content: center;
align-items: center;
}
.box {
width: 100px;
height: 100px;
background-color: #f00;
}
</style>
- transform:
css
<style>
* {
padding: 0;
margin: 0;
}
.main {
width: 400px;
height: 400px;
border: 2px solid #000;
margin: 30px auto;
position: relative;
}
.box {
width: 100px;
height: 100px;
background-color: #f00;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
- 子盒子宽高不确定(需要保证left和right的百分数一样,top和bottom的百分数一样):
html
<style>
* {
padding: 0;
margin: 0;
}
.main {
width: 400px;
height: 400px;
border: 2px solid #000;
margin: 30px auto;
position: relative;
}
.box {
background-color: #f00;
position: absolute;
left: 25%;
top: 25%;
right: 25%;
bottom: 25%;
}
</style>
<body>
<div class="main">
<div class="box"></div>
</div>
</body>