CSS三大定位技巧全解析
目录
一、前言
二、三个定位的知识点总结
1、相对定位position:relative
2.绝对定位position:absolute
3.固定定位position:fixed
三、练习
一、前言
在CSS布局中,定位是区别于标准文档流布局的核心技能,也是制作特殊布局、悬浮按钮、标签角标、弹窗的必备知识点。
很多新手分不清:相对定位、绝对定位、固定定位的区别和使用场景,今天我通过一个经典综合案例,一次性吃透三种核心定位!
二、三个定位的知识点总结
1、相对定位position:relative
.card { width: 300px; height: 200px; background-color: #ff6b6b; position:relative; }经典用法:专门作为绝对定位元素的父级参照物
经常与top、left、right、bottom搭配来微调位置,不影响整体布局
2.绝对定位position:absolute
.tag { width: 80px; height: 30px; background-color: #4dabf7; position: absolute; /* 绝对定位 */ top: 0; right: 0; }经典用法:角标、弹窗、浮窗、图片水印
通过top、left、right、bottom精准控制位置
3.固定定位position:fixed
.back-btn { width: 50px; height: 50px; background-color: #51cf66; border-radius: 50%; position: fixed; /* 固定定位 */ bottom: 30px; right: 30px; }经典用法:返回顶部按钮、悬浮客服、固定导航栏
依靠top、left、right、bottom固定在窗口角落
三、练习
根据以上学习让我们来做出下面图片的运行代码吧
大家思考的怎么样,写出的代码是否可以运行成功,下面来看看我的代码吧~
<!doctype html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>定位综合练习</title> <style> /* 练习题目:使用三种定位方式完成以下布局 1. 红色卡片:使用相对定位作为容器 2. 蓝色标签:使用绝对定位放在红色卡片右上角 3. 绿色返回按钮:使用固定定位固定在页面右下角 */ body { padding: 50px; } /* ========== 题目要求:完成下面红色卡片的样式 ========== */ .card { width: 300px; height: 200px; background-color: #ff6b6b; border-radius: 10px; padding: 20px; color: white; font-size: 18px; margin-bottom: 600px; /* 留出滚动空间 */ /* 提示:使用相对定位 */ } /* ========== 题目要求:完成下面蓝色标签的样式 ========== */ .tag { width: 80px; height: 30px; background-color: #4dabf7; border-radius: 5px; font-size: 14px; text-align: center; line-height: 30px; /* 提示:使用绝对定位,相对于card定位 */ } /* ========== 题目要求:完成下面返回按钮的样式 ========== */ .back-btn { width: 50px; height: 50px; background-color: #51cf66; border-radius: 50%; text-align: center; line-height: 50px; color: white; font-weight: bold; cursor: pointer; /* 提示:使用固定定位 */ } </style> </head> <body> <!-- 练习题目说明 --> <h2>定位综合练习 - 请完成三个盒子的样式</h2> <p>请根据CSS注释中的提示,填写正确的定位属性和偏移值</p > <hr> <!-- 红色卡片容器 - 需要添加相对定位 --> <div class="card"> 这是卡片内容 <br>请为我添加相对定位 <!-- 蓝色标签 - 需要添加绝对定位,放到右上角 --> <div class="tag">标签</div> </div> <!-- 绿色返回按钮 - 需要添加固定定位,固定在右下角 --> <div class="back-btn">↑</div> <p>(下方内容用于测试固定定位的滚动效果)</p > <div style="height: 500px; background: #f0f0f0; padding: 20px;"> 滚动页面查看绿色按钮是否保持在右下角固定位置... </div> </body> </html>