CSS三大定位技巧全解析
目录一、前言二、三个定位的知识点总结1、相对定位position:relative2.绝对定位position:absolute3.固定定位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 charsetUTF-8 meta nameviewport contentwidthdevice-width, initial-scale1.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 classcard 这是卡片内容 br请为我添加相对定位 !-- 蓝色标签 - 需要添加绝对定位放到右上角 -- div classtag标签/div /div !-- 绿色返回按钮 - 需要添加固定定位固定在右下角 -- div classback-btn↑/div p下方内容用于测试固定定位的滚动效果/p div styleheight: 500px; background: #f0f0f0; padding: 20px; 滚动页面查看绿色按钮是否保持在右下角固定位置... /div /body /html