当前位置: 移动技术网 > IT编程>网页制作>CSS > css元素水平垂直居中

css元素水平垂直居中

2019年09月02日  | 移动技术网IT编程  | 我要评论

温习一下元素水平垂直居中的几种方法

元素有具体宽度

1、absolute+负边距

.lv_center{
  border: 1px solid red;
  position: absolute;
  width: 100px;
  height: 100px;
  top:50%;
  left: 50%;
  margin-top:-原高度/2 ;
  margin-left: -原高度/2
}

2、absolute+calc

.lv_center{
  border: 1px solid red;
  position: absolute;
  width: 100px;
  height: 100px;
  top:calc(50% - 原高度/2);
  left:calc(50% - 原高度/2);
}

 3、absolute+margin auto

.lv_center{
  border: 1px solid red;
  position: absolute;
  width: 100px;
  height: 100px;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  margin: auto;
}

元素宽度不定

1、absolute+transform,css3特性2d平移

.lv_center{
  border: 1px solid red;
  position:absolute;
  top:50%;
  left:50%;
  transform:translate(-50%,-50%);
}

2、line-height,外层设置行高,内层继承行高

.box{
  line-height: 300px;
}
.lv_center{
  border: 1px solid red;
  display: inline-block;
  line-height: inherit;
  vertical-align: middle;
}

3、table-cell,模拟td特性,让元素像表格里的td

.box{
  border: 1px solid red;
  width: 300px;
  height: 300px;
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}
.lv_center{
  border: 1px solid red;
  display: inline-block;
}

4、flex弹性盒子

.lv_center{
border: 1px solid red;
  display: flex;
  justify-content: center;  //主轴对齐方式
  align-items: center;  //位于主轴中心
}

推荐一位讲得更详细的 : https://www.jianshu.com/p/1b3337214941

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网