1.给父盒子设置border 通过margin挤压
例如先给两个盒子设定父子关系
<div class="parent">
<div class="child"></div>
</div>
然后给父盒子设置border等属性
.parent {
width: 200px;
height: 200px;
background-color: blue;
border: 1px solid red;
}
然后给子盒子设置margin属性
.child {
width: 100px;
height: 100px;
background-color: red;
margin: 50px;
}
盒子就可以水平居中了

2.通过给父盒子设置padding挤压 ,给父盒子设置为边框盒子
给父盒子设置padding属性,并设置边框盒子
.parent {
width: 200px;
height: 200px;
background-color: blue;
padding: 50px;
box-sizing: border-box;
}
子盒子设置宽高背景色等基本属性
.child {
width: 100px;
height: 100px;
background-color: red;
}
这种方法也可以让盒子水平居中
3.(子绝父相)
给父盒子设置相对定位
position: relative;
给子盒子设置绝对定位 配合属性都为0
.child {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
4.(子绝父相)
给子盒子设置配合属性 top 50% ,left 50% ,margin-left:-width/2 ,margin-top:-height/2
先给父盒子设置相对定位
position: relative;
然后给子盒子设置绝对定位,也可使子盒子水平垂直居中于父盒子中
.child {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
5.给父盒子设置display:flex justify-content:center align-items:center
先给父盒子设置
.parent {
width: 200px;
height: 200px;
background-color: red;
margin: 0 auto;
display: flex;
justify-content: center;
align-items: center;
}
然后是子盒子
.child {
width: 100px;
height: 100px;
background-color: blue;
}
效果如图所示:
6.给父盒子设置display:flex 给子盒子设置margin:auto
给父盒子设置display: flex
.parent {
width: 200px;
height: 200px;
background-color: red;
margin: 0 auto;
display: flex;
}
然后给子盒子设置
.child {
width: 100px;
height: 100px;
background-color: blue;
margin: auto;
}
文章详细介绍了使用CSS将盒子居中显示的六种常见技术,包括通过margin挤压、设置padding和边框盒子、子绝父相的定位方式,以及使用flex布局。这些方法可以实现水平居中,甚至垂直居中。
3119

被折叠的 条评论
为什么被折叠?



