css盒子居中布局开发过程中是非常用的手段,虽然实现盒子居中看似简单,但是因为各种不同的情况,如盒子的大小、位置、父容器的大小等,导致选择不同的方式来实现。
body
<div class="parent">
<div class="child"></div>
</div>
// css
.parent {
width: 300px;
height: 300px;
background-color: #f0ed44;
}
.child {
width: 100px;
height: 100px;
background-color: #ee596a;
}
初始效果
css
1. 方案一:text-align + line-height
主要利用文本居中方式,将子元素转换为“行内块”元素
.parent {
text-align: center;
line-height: 300px;
}
.child {
display: inline-block;
vertical-align: middle;
}
2. 方案二:弹性布局 - flex
主要通过给父元素设置:justify-content、align-items属性
.parent {
display: flex;
justify-content: center;
align-items: center;
}
3. 方案三:弹性布局 - grid + justify-content + align-items - 父元素
.parent {
display: grid;
justify-content: center;
align-items: center;
}
4. 方案四:弹性布局 - grid -父元素、子元素
.parent {
display: grid;
}
.child {
justify-self: center; /* 水平居中 */
align-self: center; /* 垂直居中 */
}
5. 方案五:弹性布局 - flex + margin
使用display:flex弹性布局后,在主轴和交叉轴方向上都居中
.parent {
display: flex;
}
.child {
margin: auto; /* 在主轴和交叉轴方向上都居中 */
}
6. 方案六:grid + place-items
使用 grid 布局,将父元素设置为 display: grid; 并使用 place-items 属性一次性控制子元素在水平和垂直方向上的居中
.parent {
display: grid;
place-items: center; /* 在主轴和交叉轴方向上都居中 */
}
7. 方案七:position定位
通过定位的方式,先父元素偏移上左50%然后再偏移子元素的-50%
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
8. 方案八:position + margin:auto
.parent {
position: relative;
}
.child {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
9. 方案九:table-cell
设置父元素为 为 display: table-cell
.parent {
display: table-cell;
vertical-align: middle;
}
.child {
margin: auto;
}
10. 方案十: 子元素不设置宽高(ps:前面9中都是设置了宽高的)
.parent {
position: relative;
}
.child {
position: absolute;
left: 25%;
right: 25%;
top: 25%;
bottom: 25%;
}
最终的展示效果
温馨提示:在实际项目中以上涉及的方案多多少少可能会存在兼容问题不要盲目的cv,应当谨慎选择最合适的方案。
如果你还有更多好的方案请在评论区留言,咱们可以一起讨论和学习
都白嫖完了,不点赞收藏就打得你哭唧唧!!!!