css实现居中的几种方法

css实现居中的几种方法

1.通过text-align:center 和line-height:**px 实现单行水平垂直居中

.box{width: 200px;height: 200px;border: 1px solid black;
text-align:center;line-height:200px;}
	
我在居中
我无法居中

效果
css实现居中的几种方法_第1张图片
2.通过在父元素中设置display:table-cell;vertical-align:middle;来实现垂直居中

.box{width: 200px;height: 100px;border: 1px solid black;
display: table-cell;vertical-align: middle;text-align: center;}

我在居中
我也在居中

效果
css实现居中的几种方法_第2张图片
注意:
使用table-cell是最好不要与float和position:absolute一起使用,设置了table-cell的元素对高度和宽度敏感,对margin值无反应,可以响应padding的设置,表现几乎类似于一个td元素
3.通过position:absolute;的特性设置各偏移值为0,再设置margin:auto;

.box1{width: 200px;height: 100px;background-color: #059AE3;
	  position: relative;}
.box2{width: 100px;height: 50px;background-color: white;
	  position: absolute;
	  top: 0;left: 0;right: 0;bottom: 0;
	  margin: auto;}
盒子居中

同样也可以通过偏移属性和translate()函数的自身偏移来达到同样的效果
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
效果
css实现居中的几种方法_第3张图片
4.在display: flex;容器下的子元素设置margin:auto;

.box1{width:200px height:100px;border: 1px solid black;
      display: flex;}
.box2{margin: auto;}
我在居中

同样也可以在设置display: flex;的容器上使用
主轴对齐justify-content:center和侧轴对齐align-items:center来达到同样的效果
css实现居中的几种方法_第4张图片

你可能感兴趣的:(css实现居中的几种方法)