CSS绝对定位(Absolute Positioning)是指元素相对于最近的非 static 定位的祖先元素进行定位。绝对定位的元素会脱离文档流,不占据原来的空间。
position: absolute;
left: 50%;
transform: translateX(-50%);
position: absolute;
top: 50%;
transform: translateY(-50%);
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
原因:
position: relative
)。transform
属性使用不正确。解决方法:
transform
属性使用正确:transform
属性使用正确:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>绝对定位居中示例</title>
<style>
.container {
position: relative;
width: 100%;
height: 100vh;
background-color: #f0f0f0;
}
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
background-color: #ff6347;
color: white;
text-align: center;
line-height: 200px;
}
</style>
</head>
<body>
<div class="container">
<div class="centered">居中显示</div>
</div>
</body>
</html>
通过以上方法,你可以轻松实现CSS绝对定位的居中显示。
领取专属 10元无门槛券
手把手带您无忧上云