如何使一个盒子水平垂直居中

139 阅读1分钟

1.使用定位:子绝父相,给父盒子相对定位,子盒子绝对定位,top和left为50%,在margin-left : 子盒子一半px(注意必须是负值); margin-top: 子盒子高的一半px(注意必须是负值);

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

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

2.无需计算子盒子的宽高进行定位,可以使用transform: translate 移动自身的一半,实现水平垂直居中

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

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

3.使用子盒子定位时,top,left,right,bottom都设置为0,然后margin: auto; 实现水平垂直居中

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

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

4.使用flex布局,通过主轴和侧轴来实现子盒子的水平垂直居中

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

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

5.使用display:table-cell  来实现水平垂直居中

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

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