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{
  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%);
}
显示

猜你喜欢

转载自blog.csdn.net/weixin_44414901/article/details/116498881
今日推荐