马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
在网页布局中,CSS定位是实现元素精准控制的关键技能之一。通过position属性,我们可以将元素放置在页面的任何位置,并控制其相对于其他元素的举动。本文将深入剖析position属性的各个取值及其应用场景,资助你把握CSS定位的英华。
1. position属性概述
position属性用于指定元素的定位方式,它有以下几个取值:
- static:默认值,元素按照正常的文档流举行布局。
- relative:相对定位,元素相对于其正常位置举行偏移。
- absolute:绝对定位,元素相对于近来的已定位先人元素举行定位。
- fixed:固定定位,元素相对于欣赏器窗口举行定位。
- sticky:粘性定位,元素在滚动时根据设定的阈值在相对定位和固定定位之间切换。
2.相对定位relative
特点:
- 不会开释文档流;(不改变宽占位)
- 基于自身左上角的点举行定位;
- 上下左右为平移隔断;
比方:
css部分:- .div1{
- width: 200px;
- height: 200px;
- background-color: red;
- }
- .div2{
- width: 200px;
- height: 200px;
- background-color: blue;
- }
复制代码 html部分:- <div class="div1"></div>
- <div class="div2"></div>
复制代码 运行结果:
- .div1{
- width: 200px;
- height: 200px;
- background-color: red;
- }
- .div2{
- width: 200px;
- height: 200px;
- background-color: blue;
- /* 相对定位 */
- position: relative;
- left: 50px;
- }
复制代码 在div2的css中设置相对定位,而且设置隔断左边50px,如下图所示:
应用场景:
- 微调元素位置,使其与附近元素对齐。
- 作为绝对定位元素的参考点。
3.绝定定位absolute
特点:
- 会开释文档流;
- 判定父视图是否带有定位属性,假如有,则相对于其父视图左上角的原点举行定位;假如没有,就找父视图的父,以此类推,直到找到再根据其左上角的原点举行定位;(若都无父视图,那就把body看成父视图,根据网页的左上角为原点举行定位)
- 上下左右为与父视图的隔断;
比方:- <style>
- .div1{
- width: 200px;
- height: 200px;
- background-color: red;
- }
- .div2{
- width: 200px;
- height: 200px;
- background-color: yellow;
- }
- .div3{
- width: 200px;
- height: 200px;
- background-color: green;
- }
- </style>
- </style>
- </head>
- <body>
- <div class="div1"></div>
- <div class="div2"></div>
- <div class="div3"></div>
- </body>
复制代码 运行结果:
如今对div2加入绝对定位,而且隔断左边100px,隔断上面100px。- .div2{
- width: 200px;
- height: 200px;
- background-color: yellow;
- /* 绝对定位 */
- position: absolute;
- left: 100px;
- top:100px;
- }
复制代码 运行结果为:
应用场景:
- 创建浮动元素,如提示框、下拉菜单等。
- 实现复杂的布局结果,如重叠元素、层叠卡片等。
4.固定定位fixed
特点:
- 开释文档流;
- 基于屏幕固定定位
- 上下左右为与屏幕四边的隔断
比方:- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- <style>
- .div01 {
- height: 200px;
- width: 200px;
- background-color: red;
- }
- .div02 {
- height: 200px;
- width: 200px;
- background-color: rgb(206, 233, 73);
- }
- .div22{
- height: 400px;
- width: 400px;
- background-color: pink;
- }
- .div03 {
- height: 200px;
- width: 200px;
- background-color: rgb(69, 60, 205);
- position: fixed;
- bottom: 200px;
- right: 40px;
- }
- .div04 {
- height: 200px;
- width: 200px;
- background-color: rgb(171, 140, 140);
- }
-
- </style>
- </head>
- <body>
- <div class="div01"></div>
- <div class="div22">
- <div class="div02"></div>
- </div>
-
- <div class="div03"></div>
- <div class="div04"></div>
- <div class="div04"></div>
- <div class="div04"></div>
- <div class="div04"></div>
- <div class="div04"></div>
- </body>
- </html>
复制代码 运行结果:
应用场景:
- 创建固定的导航栏、页脚等。
- 实现悬浮按钮、回到顶部按钮等。
总结
CSS定位是网页布局中不可或缺的工具,把握position属性的各个取值及其应用场景,可以资助你实现更加机动和复杂的布局结果。在现实开发中,应根据具体需求选择符合的定位方式。
渴望本文能资助你更好地明白和应用CSS定位,提升你的网页布局本领。假如你有任何题目或发起,接待在品评区留言讨论!
|