批改状态:合格
老师批语:
<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>定位的类型与原理</title></head><body><!--! 定位布局* 1. 定位三个必知术语: 定位元素, 最初包含块(定位上下文/html), 参照物(1). 定位元素: position: relative / absolute / fixed(2). 最初包含块: 包含了<html>的不可见的,但可感知的区块,大多场景下与"视口"表现一致,但并不相同(3). 参照物: 自身, 祖先定位元素, 最初包含块* 2. 页面坐标系(1) 与数学坐标每系不同(2) 以左上角为起始点,坐标(0,0)(3) 向右, X 变大, 向下, Y 变大(4) 页面四个顶点用: top,left,right,bottom表示* 3. 定位类型: 相对, 绝对, 固定, 默认静态(1). 相对定位: position: relative(2). 绝对定位: position: absolute(3). 固定定位: position: fixed(4). 静态定位: position: static (浏览器默认,即文档流布局)* 4. 定位元素:(1): 定义: 也叫"可定位元素",即可以在文档流中自定义元素的排列方向(2): 属性: position: relative / absolute / fixed,即 非static即可* 5. 定位参照物:(1): 相对定位: 相对于"自身在文档流中的位置"(2). 绝对定位: 相对于"距离它最近的定位元素的位置",即常说的"定位父级",逐级向上直到最初包含块(3). 固定定位: 总是相对于"最初包含块"定位--><!-- 1. 相对定位 --><div class="box box1"><div class="item relative">相对定位</div><div>Hello</div></div><style>.box {border: 1px solid #000;height: 200px;width: 200px;background-color: lightcyan;}.item {height: 50px;width: 100px;border: 1px solid #000;}/* 相对定位 */.box.box1 .item.relative {background-color: lightgreen;/* 默认静态定位 */position: static;/* 将文档流中的元素转为"定位元素" *//* position: 只要不是static; */position: relative;top: 20px;left: 20px;/* 相对定位,元素仍在文档流中,受文档布局限制(源码顺序) *//* 只是相对原始位置发生了偏移而已 */}</style><hr /><!-- 2. 绝对定位 --><div class="box box2"><div class="item absolute">绝对定位</div></div><style>.box.box2 .item.absolute {background-color: wheat;/* 绝对定位 */position: absolute;/* 定位偏移量 */top: 20px;left: 20px;/* 绝对定位元素,总是相对于它的祖先定位元素进行定位 *//* ! 因为父级没有定位元素,所以逐级向上查询,直到html */}/* 我们将它的父级转为定位元素 */.box.box2 {/* 实际工作中, relative用得极少, 除了当定位参考父级 */position: relative;/* position: absolute; */}/* 垂直水平居中 */.box.box2 .item.absolute {top: 0;left: 0;right: 0;bottom: 0;margin: auto;}/* .box.box2 .item.absolute {transform: translate(25%, 75%);} */</style><hr /><!-- 3. 固定定位 --><div class="box box3"><div class="item fixed">固定定位</div></div><style>.box.box3 .item.fixed {background-color: violet;width: 100vw;/* 固定定位,总是相对于一个固定的定位参考父级,html */position: fixed;/* top: 0;left: 0; */right: 0;bottom: 0;}.box.box3 {/* 固定定位不是相对于父级 */position: relative;}/* 适合于做固定位置的导航, 楼层, 客服 */body {height: 2000px;}/**** 1. 相对定位: 静态定位的特例,还在文档流* 2. 绝对定位: 相对于具有定位属性的祖先元素定位* 3. 固定定位: 总是相对于html定位(看成绝对定位的一个特例)**/</style></body></html>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号