position 定位模型
CSS 的 position 属性决定元素的定位方式,配合 top、right、bottom、left 属性可精确控制元素位置。
1. 静态定位(static)
- 默认值,元素按正常文档流排列。
top、left等属性无效。
position: static;
2. 相对定位(relative)
- 元素保持在文档流中,但可相对自身正常位置偏移。
- 偏移不会影响其他元素布局。
position: relative;
top: 10px;
left: 20px;
3. 绝对定位(absolute)
- 元素脱离文档流,定位相对于最近的已定位父元素(非 static)。
- 可使用
top、left等属性精确定位。 - 不占据空间,可能覆盖其他内容。
position: absolute;
top: 0;
right: 0;
4. 固定定位(fixed)
- 元素脱离文档流,定位相对于浏览器窗口固定位置。
- 滚动页面时元素位置不变。
position: fixed;
bottom: 10px;
right: 10px;
5. 粘性定位(sticky)
- 介于相对定位和固定定位之间。
- 元素在滚动到设定阈值时固定位置。
position: sticky;
top: 0;
position 定位示例
源码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>position 定位示例</title>
<style>
.static {
position: static;
background-color: #c5cae9;
padding: 10px;
margin-bottom: 10px;
}
.relative {
position: relative;
top: 10px;
left: 20px;
background-color: #ffe082;
padding: 10px;
margin-bottom: 10px;
}
.absolute-container {
position: relative;
height: 150px;
background-color: #b2dfdb;
margin-bottom: 10px;
}
.absolute {
position: absolute;
top: 10px;
right: 10px;
background-color: #ffab91;
padding: 10px;
width: 120px;
}
.fixed {
position: fixed;
bottom: 10px;
right: 10px;
background-color: #90caf9;
padding: 10px;
width: 150px;
text-align: center;
color: #fff;
}
.sticky-container {
height: 200px;
overflow: auto;
border: 1px solid #999;
margin-top: 20px;
padding: 10px;
}
.sticky {
position: sticky;
top: 0;
background-color: #aed581;
padding: 5px;
font-weight: bold;
}
.content {
height: 400px;
background: linear-gradient(to bottom, #fff, #ddd);
margin-top: 10px;
}
</style>
</head>
<body>
<div class="static">静态定位 (static)</div>
<div class="relative">相对定位 (relative),向下右偏移</div>
<div class="absolute-container">
<div>父元素相对定位容器</div>
<div class="absolute">绝对定位 (absolute),右上角</div>
</div>
<div class="sticky-container">
<div class="sticky">粘性定位 (sticky),顶部固定</div>
<div class="content">内容区域,滚动查看效果</div>
</div>
<div class="fixed">固定定位 (fixed),浏览器右下角</div>
</body>
</html>
相关内容
- 什么是 CSS? CSS(层叠样式表)是一种用来描述网页外观样式的语言。它定义了如何为HTML元素设置颜色、字体、布局等视觉效果,使网页更加美观和易于阅读。
- CSS 的作用与工作原理 介绍CSS的主要作用及其工作原理,帮助理解如何通过样式表控制网页元素的外观和布局,实现内容与表现的分离。
- CSS 的引入方式 介绍CSS的三种主要引入方式:内联样式、内部样式表和外部样式表,帮助开发者选择合适的方法应用样式。
- 基本语法结构 介绍CSS的基本语法结构,包括选择器、属性和属性值的组成方式,帮助理解如何编写有效的样式规则。
- 注释的使用方式 介绍CSS中注释的写法和作用,帮助开发者在样式代码中添加说明,提高代码可读性和维护性。
- 基本选择器 介绍CSS中最基础的三种选择器:元素选择器、类选择器和ID选择器,是学习CSS样式编写的基础。