CSS定位详细说明以及案例
2025-03-11
31
参考资料
CSS 定位属性用于控制元素的布局位置。常用的定位方式包括 static、relative、absolute、fixed 和 sticky。
1. static(默认定位)
元素按照正常的文档流排列,top、right、bottom、left 和 z-index 属性无效。
div {
position: static;
}2. relative(相对定位)
元素相对于其正常位置进行定位,不影响其他元素布局。
div {
position: relative;
top: 10px;
left: 20px;
}3. absolute(绝对定位)
元素相对于最近的非 static 定位的祖先元素定位,若无则相对于 <body>。
div {
position: absolute;
top: 50px;
left: 100px;
}4. fixed(固定定位)
元素相对于视口定位,不随页面滚动移动。
div {
position: fixed;
top: 0;
right: 0;
}5. sticky(粘性定位)
元素根据滚动位置在 relative 和 fixed 之间切换。
div {
position: sticky;
top: 0;
}案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Positioning</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: lightblue;
margin: 10px;
text-align: center;
line-height: 100px;
}
.relative {
position: relative;
top: 20px;
left: 30px;
}
.absolute {
position: absolute;
top: 50px;
left: 150px;
}
.fixed {
position: fixed;
top: 10px;
right: 10px;
}
.sticky {
position: sticky;
top: 0;
background-color: lightcoral;
}
</style>
</head>
<body>
<div class="box">Static</div>
<div class="box relative">Relative</div>
<div class="box absolute">Absolute</div>
<div class="box fixed">Fixed</div>
<div style="height: 1000px;">
<div class="box sticky">Sticky</div>
</div>
</body>
</html>总结
static:默认定位,元素按正常文档流排列。relative:相对于正常位置定位。absolute:相对于最近的非static祖先元素定位。fixed:相对于视口定位。sticky:根据滚动位置切换relative和fixed。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。
本文来自《西里网 . html 网页设计》 -- 发布时间:2025-03-29
本页链接:https://html.ciilii.com/show/news-213.html
原创声明:本篇文章均为西里网原创,由《DeepSeek-R1 模型》自动生成。内容真实性仅供参考学习。
本作品采用 知识共享署名—非商业性使用—相同方式共享 4.0 国际许可协议 (CC BY-NC-SA 4.0) 进行许可。
