让盒⼦居中的⼏种常⽤的⽅式~
结构:
<div class="wrapper">
<div class="box"></div>
</div>
样式⼀,也是最传统的⽅法,使⽤定位,需要知道⾃⾝的宽⾼:
.wrapper{
position: relative;
width: 400px;
height: 400px;
background-color: aqua;
}
flex布局对齐方式.box{
position: absolute;
width: 100px;
height: 100px;
background-color: red;
left: 50%;
top:50%;
margin-left: -50px;
margin-top: -50px;
}
样式⼆,使⽤定位,使⽤css3新特效translate:
.wrapper{
position: relative;
width: 400px;
height: 400px;
background-color: aqua;
}
.box{
position: absolute;
width: 100px;
height: 100px;
background-color: red;
left: 50%;
top:50%;
transform: translate(-50%,-50%);
}
样式三,利⽤flex(弹性布局):
.wrapper{
display: flex;
width: 400px;
height: 400px;
background-color: aqua;
justify-content: center;
align-items: center;
}
.box{
width: 100px;
height: 100px;
background-color: red;
}
样式四,使⽤定位,可以不知道⾃⾝宽⾼,但是你设置的时候必须要有宽⾼: .wrapper{
display: flex;
width: 200px;
height: 400px;
background-color: aqua;
position: relative;
}
.box{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
样式五,利⽤justify-content:space-around;(⽤的极少):
.wrapper{
display: flex;
width: 400px;
height: 400px;
background-color: aqua;
/*justify-content: space-between;  (左右两边对齐)*/
justify-content: space-around;
align-items: center;
}
.box{
width: 100px;
height: 100px;
background-color: red;
}
样式六,利⽤display: table-cell; vertical-align: middle:
.wrapper{
display: flex;
width: 400px;
height: 400px;
background-color: aqua;
display: table-cell;
vertical-align: middle;
}
.box{
width: 100px;
height: 100px;
background-color: red;
margin: auto;
}
⽅式。。。。。。。。。。。。。。。。
flex扩展:
justify-content: center; ⽔平居中
justify-content: space-between; 两端对齐
justify-content: space-between; 两端对齐
justify-content: space-around; 盒⼦四周距离相等(可以⽤来居中)justify-content: flex-start; 左端对齐
justify-content: flex-end; 右端对齐

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。