<body>
<div class="main">
<div class="box"></div>
</div>
</body>
- 绝对定位加
margin: auto;
:
<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:
<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 推动:
<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 居中:
<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:
<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的百分数一样):
<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>
文章来源地址https://www.toymoban.com/news/detail-742347.html
文章来源:https://www.toymoban.com/news/detail-742347.html
到了这里,关于【CSS】div 盒子居中的常用方法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!