CSS中关于div的对齐⽅式
关于DIV的⼏种对齐⽅式
常见问题:⼀个盒⼦在另⼀个盒⼦⾥⾯咋么,怎么让他⽔平居中
1.Flex ⽅法
将⽗元素设设置为弹性布局:display: flex
再设置属性:justify-content: center(justify-content ⽤于设置或检索弹性盒⼦元素在主轴(横轴)⽅向上的对齐⽅式。)再设置属性:align-items: center;(align-items 属性定义flex⼦项在flex容器的当前⾏的侧轴(纵轴)⽅向上的对齐⽅式。)
display: flex;
justify-content: center;
align-items: center;
text-align: center;
2.position定位⽅法
要先采⽤绝对定位position:absolute,若改为相对定位position:relative;则只会左右居中,不会上下居中。
.test{
background-color: red;
width:100px;
height:100px;
position:relative;
margin:200px auto;
}
.test1{
flex布局对齐方式height:50px;
width:50px;
background-color:pink;
position:absolute;
text-align: center;
line-height:50px;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
显⽰3.position+transform ⽅法
.定位+transform(不需要知道⼦盒⼦的宽⾼)
.test{
background-color:red;
width:100px;
height:100px;
position:relative;
}
.test1{
height:50px;
width:50px;
background-color:pink;
position:absolute;
top:50%;
left:50%;
transform: translate(-50% ,-50%);
}
显⽰