CSS平移实现居中效果
常规
以下代码,平移之后减去盒子自身尺寸
div {
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -50px;
background-color: pink;
width: 200px;
height: 100px;
}
平移实现
无需计算,向左向上移动盒子的一半
margin-left: -100px; margin-top: -50px;替换为transform: translate(-50%,-50%);即可
代码
.box {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
background-color: pink;
width: 200px;
height: 100px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>平面转换-平移</title>
<style>
/* div {
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -50px;
width: 200px;
background-color: pink;
height: 100px;
} */
.box {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
background-color: pink;
width: 200px;
height: 100px;
}
</style>
</head>
<body>
<div class="box">
</div>
</body>
</html>