CSS 固定定位 position fixed

本文详细介绍了CSS中的固定定位,包括其基本概念、如何使用及坐标系的变化方式,并提供了多个示例帮助理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单描述:固定定位是将某个元素固定在浏览器的某个确定的位置,不随滚动条的移动而变化;

                注意:固定定位的位置是  相对当前浏览器窗口  的;

代码示例:

1.我们先在页面中输出一个标准情况下的 div 元素,不添加定位;

 代码:

<!doctype html>
<html>
     <head>
          <meta charset="utf-8">
          <title></title>
          <style>
              *{margin:0;padding:0;}
             .abc{width:200px; height:200px; background-color:red; border:2px solid yellow;}
          </style>
     </head>
     <body>
            <div class="abc"></div>
     </body>
</html>

 显示如下:


2.   然后给 div 元素添加固定定位:设置 position:fixed; left:100px;  top:100px;

代码:

<!doctype html>
<html>
     <head>
          <meta charset="utf-8">
          <title></title>
          <style>
              *{margin:0;padding:0;}
             .abc{width:200px; height:200px; background-color:red; border:2px solid yellow;
             position:fixed; left:100px; top:100px;}
          </style>
     </head>
     <body>
            <div class="abc"></div>
     </body>
</html>

显示:


3.我们再次修改定位: position:fixed;  right:100px;  top:100px;

 显示效果:


可以看出坐标系是不断变化的,

那么:  left  +  top: 相对于 左 上 顶点进行位移

            left+bottom:相对于 左 下 顶点进行位移

            right +top:相对于 右 上 顶点进行位移

            right +bottom:相对于 右 下 顶点进行位移


### CSS Fixed 定位详解 #### 什么是Fixed定位? `position: fixed;` 创建固定定位的元素,相对于浏览器窗口进行定位。这意味着即使页面滚动,该元素也会保持在视窗中的同一位置[^1]。 #### 如何定义Fixed定位? 要创建一个具有 `fixed` 定位特性的 HTML 元素,需应用如下样式: ```css #example { position: fixed; top: 10px; left: 20px; } ``` 上述代码片段中,ID名为 example 的 div 将被放置于距离浏览器窗口顶端 10 像素、左侧边缘 20 像素之处,并且无论用户怎样上下或左右滚动网页,此 div 都不会移动。 #### 实现全屏导航栏实例 为了展示如何利用 `position: fixed` 构建实用场景下的布局方案,下面给出一段用于构建始终位于屏幕顶部的导航条的例子: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Fixed Navigation Bar Example</title> <style> body { margin: 0; font-family: Arial, sans-serif;} .navbar { background-color: #333; overflow: hidden; color: white; padding: 14px 16px; text-align: center; /* 设置为固定定位 */ position: fixed; width: 100%; top: 0; } .content { padding-top: 70px; /* 确保主要内容不在navbar后面 */ } </style> </head> <body> <div class="navbar">我的网站名称</div> <div class="content"> <p>一些文本...</p><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <p>更多文本...</p> </div> </body> </html> ``` 这段HTML文档展示了如何使用 `position: fixed` 来制作一个固定的导航栏,它始终保持在页面最上方,不影响其他内容区域的内容流动。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值