盒模型大法好!轻松实现CSS居中样式
最编程
2024-02-13 08:20:34
...
前言
在我们的面试和工作中,偶尔会问到关于"让盒子水平居中的几种方法"的问题,虽然问题不难,但是我们还是有必要掌握的,下面一起来看看这几种方法吧!
方法一 margin : auto
使用定位和 margin : auto 的方法让盒子水平垂直居中
<style>
.father {
position: relative;
width: 400px;
height: 400px;
border: 3px solid #000;
margin: 20px auto;
}
.son {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
width: 150px;
height: 80px;
background: hotpink;
}
</style>
方法二 transform位移
先给父盒子相对定位,然后给子盒子相对定位,偏移量都为50%,最后让盒子位移自身高度的一半。
<style>
.father {
position: relative;
width: 400px;
height: 400px;
border: 2px solid black;
}
.son {
position: absolute;
left: 50%;
top: 50%;
width: 100px;
height: 100px;
background-color: pink;
transform: translate(-50%, -50%);
}
方法三 子绝父相
先给父盒子设相对定位,给子盒子设绝对定位,偏移量为50%,最后设置外边距为自身宽度的负一半的值。
<style>
.father {
position: relative;
width: 400px;
height: 400px;
border: 2px solid black;
}
.son {
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
width: 100px;
height: 100px;
background-color: pink;
}
</style>
方法四 flex布局
使用flex布局的主轴和侧轴居中来让子盒子水平垂直居中对齐。
<style>
.father {
display: flex;
justify-content: center;
align-items: center;
width: 400px;
height: 400px;
border: 2px solid black;
}
.son {
width: 100px;
height: 100px;
background-color: pink;
}
</style>
方法五 table-cell 布局
直接利用table-cell布局完成盒子的水平垂直居中
<style>
.father {
width: 200px;
height: 200px;
background-color: red;
display: table-cell;
vertical-align: middle;
}
.son {
display: inline-block;
margin-left: 100px;
width: 100px;
height: 100px;
background-color: blue;
}
</style>