transform+posistion实现盒子的水平垂直居中
<!DOCTYPE html>
<html lang="ch">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>transform水平垂直居中</title>
</head>
<style>
div {
width: 600px;
height: 600px;
background-color: pink;
/*父相*/
position: relative;
}
p{
width: 200px;
height: 200px;
background-color: purple;
/*子绝*/
position: absolute;
/*先用定位移动大盒子的水平/垂直一半位置*/
top: 50%;
left: 50%;
/*再用变形移动自身水平/垂直负一半,即刚好居中;
之前用margin-left:-100px;,margin-top:-100px;*/
transform: translate(-50%,-50%);
}
span{
/*变形对行内元素无效*/
transform: translate(52px,0);
}
</style>
<body>
<div>
<p></p>
</div>
<span>asdf</span>
</body>
</html>
效果: