CSS平移实现居中效果
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>
原文地址:https://blog.csdn.net/m0_73701759/article/details/140859068
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!