css总结:盒子水平垂直居中的几种方案

定位(三种)

  • 定位1
  1. 外层body的定位方式设置成相对定位 position:relative;
  2. 内层盒子的定位方式设置成绝对定位 position:absolute;
  3. 内层盒子的topleft都设置为50%
  4. 如果知道内层盒子的具体宽高,再设置其margin-topmargin-left(属性值为负的内层盒子宽高的一半)
	body{
		position:relative;
	}
	
	.box{
		position:absolute;
		top:50%;
		left:50%;
		margin-top:-25px;
		margin-left:-50px;
	}
  • 定位2
  1. 补充:如果不想去考虑内层盒子的宽高大小,可以将内层盒子的topleftrightbottom都设置为0,然后加上margin:auto;也能实现居中效果。(注意此方法只是没有涉及到具体的宽高值,但是要求内层盒子本身是具有宽高值的)
	body{
		position:relative;
	}
	
	.box{
		position:absolute;
		top:0;
		left:0;
		right:0;
		bottom:0;
		margin:auto;
	}
  • 定位3
  1. 重要:利用transform来调整元素的移动(它的兼容性没有特别好)
	body{
		position:relative;
	}
	
	.box{
		position:absolute;
		top:50%;
		left:50%;
		transform:translate(-50%,50%);
	}

display:flex(尤其在移动端开发中特别方便)

  1. 将父容器的display设置为flex
  2. 然后设置justify-contentalign-items(在这里主轴是默认是x轴,即水平方向,通过justify-content设置;align-items在此场景下用来设置垂直方向上的居中。)
	body{
		display:flex;
		justify-content:center;
		align-items:center;
	}

Javascript

(HTML的宽高-盒子的宽高)/2+‘px’(简单描述一下,不写了)

display:table-cell(本身是用来控制文本的居中,不常用)

  • 此方法要求父级元素有固定宽高
	body{
		display:table-cell;
		vertical-align:middle;
		text-align:center;
		/*固定宽高*/
		width:500px;
		height:500px;
		background:lightblue;
	}
	
	.box{
		/*需要把盒子设置为行级元素*/
		display:inline-block;
	}

猜你喜欢

转载自blog.csdn.net/wennianzhu/article/details/107405412