参会人:@鹿维恩
会议时间:2022-01-20
会议地点:3 号会议室
定位
元素定位
- 确定目标元素
- 坐标系
- 定位流
定位的属性 position
- static 默认 元素不定位, 在正常文档流
- relative相对定位 相对于元素本身在浏览器的位置去定位
- absolute绝对定位相对于包含块定位
- fixed固定定位相对于窗口定位
- sticky粘性定位参考临界值(css3)
- relative相对定位 相对于元素本身在浏览器的位置去定位
偏移属性
只有设置了定位属性(属性不是默认值 )的元素才可以添加偏移属性
定位属性和偏移属性必须一起使用
相对定位
position: relative
配合偏移属性: top\right\bottom\left
相对定位的特点
- 参考位置: 相对于元素自身在浏览器的位置进行定位
- 相对定位不脱离文档流, 在正常的文档流里面的位置会保留
- 支持负值
绝对定位
position: absolute
配合偏移属性: top\right\bottom\left
绝对定位的特点:
- 参考位置: 相对于包含块定位
- 有定位属性并且属性值不是默认值的父元素
- 支持负值
- 脱离文档流, 在正常的文档流里面的位置不保留
- 子绝父相: 子元素绝对定位, 父元素相对定位
绝对定位的参考位置
相对于包含块(有定位属性值不是默认值的父元素)
- 如果父元素没有定位属性, 那么该元素会继续往上找, 直到找到最近的有定位属性并且属性值不是默认值得祖先级元素
- 如果绝对定位的元素的祖先级元素都没有定位属性, 那么该元素会参考浏览器的左上角位置定位
固定定位
position: fixed
配合偏移属性: top\bottom\left\right
固定定位的特点
- 相对于浏览器的可视区域左上角定位
- 脱离文档流
<style>
.box1{
width: 200px;
height: 200px;
background-color: pink;
position: fixed;
left: 20px;
top: 20px;
}
.box2{
width: 200px;
height: 200px;
background-color: skyblue;
/* position: fixed; */
}
</style>
<div class="box1"></div>
<div class="box2"></div>
偏移属性
top\right\bottom\left
- auto 默认值 元素处于原来的文档流中的位置不变
- 数值
- 百分比
- 相对定位: 参考元素的宽高
- 绝对定位: 参考包含块的宽高
- 固定定位: 参考窗口的宽高
<style>
.box1 {
width: 300px;
height: 300px;
background-color: green;
position: relative;
}
.box2 {
/* width: 200px; */
/* height: 200px; */
background-color: pink;
position: absolute;
left: 10px;
right: 20px;
top: 10px;
bottom: 10px;
}
</style>
<div class="box1">
<div class="box2"></div>
</div>
**小结: **
- 当一个元素已经设置了宽高,同时设置四个偏移属性的时候, 以top和left为准
- 当一个元素没有设置高度的时候,同时设置top和bottom, 会拉伸自己以适应top和bottom
- 当一个元素没有设置宽度的时候,同时设置left和right, 会拉伸自己以适应left和right
- 当一个元素没有设置高度和宽度的时候,同时设置top和bottom和left和right, 会拉伸自己以适应top和bottom和left和right
粘性定位(css3)
position: sticky
特点:
- 临界点
- 不脱离文档流
<style>
.header{
width: 100%;
height: 90px;
background-color: aquamarine;
position: sticky;
top: 0;
}
.banner{
width: 100%;
height: 400px;
background-color: black;
}
</style>
**小结: **浮动, 绝对定位, 固定定位的元素可以直接设置宽高
**原因: **因为脱离文档流, 不再遵循默认文档流的元素类型
层级: 定位元素之间的层叠关系
z-index:
- auto 默认等同于0
- 直接设置没有单数的整数 也可以设置负值
- 数值越大越靠前
- 数值相同时, 看书写顺序
- 负值不推荐使用
- 跨度尽量10以上
- 最大值是21亿多
<style>
.box1{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 0;
top: 0;
z-index: 30;
}
.box2{
width: 200px;
height: 200px;
background-color: skyblue;
position: absolute;
left: 20px;
top: 20px;
z-index: 20;
}
.box3{
width: 300px;
height: 300px;
background-color: orange;
position: absolute;
left: 40px;
top: 40px;
z-index: 10;
}
</style>