CSS 定位元素
cssweb developmentfront end technology更新于 2025/11/27 2:52:17
position 属性用于定位元素。例如,以下元素为定位元素 −
static − 元素框作为正常文档流的一部分进行布局,位于前一个元素之后,并位于后续元素之前。
relative − 元素框作为正常流的一部分进行布局,然后偏移一定距离。
absolute − 元素框相对于其包含块进行布局,并完全脱离文档的正常流。
fixed −元素的框是绝对定位的,具有所有在position:absolute中描述的行为。
以下是使用CSS定位元素的代码 −
示例
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
div {
color: white;
text-align: center;
height: 100px;
width: 100px;
}
.static {
position: static;
background-color: greenyellow;
}
.relative {
position: relative;
left: 50px;
background-color: rgb(255, 47, 47);
}
.absolute {
position: absolute;
right: 50px;
top: 20px;
background-color: hotpink;
}
</style>
</head>
<body>
<h1>Position elements example</h1>
<div class="static">STATIC</div>
<div class="relative">RELATIVE</div>
<div class="absolute">ABSOLUTE</div>
</body>
</html>
输出
上述代码将产生以下输出 −

相关文章
有用资源
css 参考教程 - 该教程包含有关 css 的更多信息:https://www.cainiaomax.com/css/

