前端学习笔记 - CSS - 3.垂直水平居中

初始化html/css

<style type="text/css">
	*{
		margin: 0;
		padding: 0;
	}
	.box1{
		width: 400px;
		height: 400px;
		background-color: skyblue;
		position: relative;
	}
    .box2{
		width: 200px;
		height: 200px;
		background-color: aliceblue;
	}	
</style>
<body>
	<div class="box1" id="parent">
		<div class="box2" id="son">
		
		</div>
	</div>
</body>

前端学习笔记 - CSS - 3.垂直水平居中_第1张图片

垂直水平居中

前端学习笔记 - CSS - 3.垂直水平居中_第2张图片

方案一:绝对定位+margin

1.知道宽高的情况下

#son{
		position: absolute;
		margin-top: 100px;
		margin-left: 100px;
	}

2.不知道宽高的情况下(margin:auto)

#son{
		position: absolute;
		top: 0;
		bottom: 0;
		right: 0;
		left: 0;
		margin: auto;
	}

3.知道宽高的情况下(定位+偏移)

#son{
		position: absolute;
		top: 50%;
		left: 50%;
		margin-top: -100px; /* 上移自身一半*/
		margin-left: -100px; /* 左移自身一半 */
	}

方案二:绝对定位+transform

#son{
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);  /* 平移 */
	}

方案三:新旧版本的flex

1.新版本flex

#parent{
			display: flex;
			justify-content: center; /* 水平居中 */
			align-items: center;  /* 垂直居中 */
		}

2.旧版本flex

#parent{
			display: -webkit-box;
			-webkit-box-pack: center;  /* 水平居中 */
			-webkit-box-align: center;   /* 垂直居中 */
		}

你可能感兴趣的:(前端,css,css3)