
欢迎来到《从基础到辉煌》课程第十一讲。在本次讲座中,我们将探讨css定位的不同类型:相对、绝对、固定和粘性。了解定位可以让您控制元素在页面上的显示位置以及用户与内容交互时元素的行为方式。
position 属性指定元素在文档中的位置。它可以采用以下值:
具有position:relative的元素相对于其原始(静态)位置定位。它保留在文档流中,这意味着其他元素仍会考虑它。
.box {
position: relative;
top: 20px; /* moves the box 20px down from its normal position */
left: 30px; /* moves the box 30px to the right */
}
在此示例中,元素从原始位置向下移动 20px,向右移动 30px,但保留其在文档流中的空间。
立即学习“前端免费学习笔记(深入)”;
位置为绝对的元素将从文档流中删除,并相对于其最近的定位祖先(即位置不是静态的祖先)进行定位。
.container {
position: relative; /* this container is the reference for the absolute positioning */
width: 300px;
height: 200px;
background-color: #f4f4f4;
}
.box {
position: absolute;
top: 50px;
right: 20px;
background-color: #333;
color: white;
padding: 10px;
}
在此示例中:
位置为固定的元素相对于浏览器窗口定位,无论页面如何滚动。
.navbar {
position: fixed;
top: 0;
left: 0;
width: 100%;
background-color: #333;
color: white;
padding: 15px;
text-align: center;
}
在此示例中:
具有position: sticky 的元素被视为相对元素,直到用户滚动超过定义的阈值,此时它变得固定。
.header {
position: sticky;
top: 0;
background-color: #333;
color: white;
padding: 10px;
}
在此示例中:
当元素被定位(相对、绝对、固定或粘性)时,您可以使用 z-index 属性控制它们的堆叠顺序。较高的 z-index 值使元素出现在较低的元素之上。
.box1 {
position: absolute;
top: 50px;
left: 50px;
z-index: 1; /* lower z-index */
background-color: #f4f4f4;
padding: 20px;
}
.box2 {
position: absolute;
top: 80px;
left: 80px;
z-index: 2; /* higher z-index */
background-color: #333;
color: white;
padding: 20px;
}
在此示例中:
您可以组合定位值来创建高级布局。
.sidebar {
position: fixed;
top: 0;
left: 0;
width: 200px;
height: 100vh;
background-color: #333;
color: white;
padding: 20px;
}
.content {
position: relative;
margin-left: 220px; /* Account for the fixed sidebar */
padding: 20px;
}
在此布局中:
下一步:在下一堂课中,我们将深入探讨css 变换和动画,您将在其中学习如何轻松为 web 元素设置动画。准备好让您的设计充满活力和互动!
在 linkedin 上关注我
里多伊·哈桑
以上就是CSS 定位 – 绝对、相对、固定和粘性的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号