让一个盒子水平垂直居中的方法

918 阅读1分钟

1.通过定位,给父盒子相对定位,子盒子绝对定位,top,left为50%,在margin-left : -(子盒子一半)px; margin-top: -(子盒子高的一半)px;

<style>
		div {
			position: relative;
			height: 400px;
			width: 400px;
			background-color: pink;
		}

		span {
			position: absolute;
			top: 50%;
			left: 50%;
			margin-left: -50px;
			margin-top: -50px;
			display: block;
			width: 100px;
			height: 100px;
			background-color: purple;
		}
</style>

2.不依赖通过计算子盒子的宽高进行定位,可以用transform: translate 移动自身的一半就行了

<style>
		div {
			position: relative;
			height: 400px;
			width: 400px;
			background-color: pink;
		}

		span {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			display: block;
			width: 100px;
			height: 100px;
			background-color: purple;
		}
</style>

3.子盒子定位时,top,left,right,bottom都设置为0,然后margin: auto; 也能实现居中

 <style>
		div {
			position: relative;
			height: 400px;
			width: 400px;
			background-color: pink;
		}

		span {
			position: absolute;
			top: 0;
			left: 0;
			bottom: 0;
			right: 0;
			margin: auto;
			display: block;
			width: 100px;
			height: 100px;
			background-color: purple;
		}
</style>

4.通过flex布局,设置垂直水平都居中

<style>
		div {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 400px;
			width: 400px;
			background-color: pink;
		}

		span {
			display: block;
			width: 100px;
			height: 100px;
			background-color: purple;
		}
</style>

5.通过display:table-cell   注: 子盒子要设置为 display:inline-block;

<style>
		div {
			display:table-cell;
            vertical-align:middle;
            text-align:center;
			height: 400px;
			width: 400px;
			background-color: pink;
		}

		span {
			display:inline-block;
			width: 100px;
			height: 100px;
			background-color: purple;
		}
</style>