CSS定位
网页中常见的布局方式:
标准流:
- 块级元素独占一行------垂直布局
- 行内元素/行内块元素一行显示多个------水平布局
浮动:
- 可以让原本垂直布局的块级元素变成水平布局
定位:
- 可以让元素自由的摆在网页的任意位置
- 一般用于盒子之间的层叠情况
定位的常见应用场景:
-
可以解决盒子与盒子之间的层叠问题,定位之后的元素层级最高,可以层叠在其他盒子上面
-
可以让盒子始终固定在屏幕中的某个位置
定位的使用步骤:
设置定位方式:
-
属性名:position
-
常见的属性值:
定位方式 属性值 静态定位 static 相对定位 relative 绝对定位 absolute 固定定位 fixed
设置偏移值:
-
偏移值设置分两个方向,水平和垂直方向各选一个即可
-
选取的原则一般是就近原则(离哪边近用哪个)
方向 属性名 属性值 含义 水平 left 数字+px 距离左边的距离 水平 right 数字+px 距离右边的距离 垂直 top 数字+px 距离上边的距离 垂直 bottom 数字+px 距离下边的距离
举例:
-
设置两个盒子:box1和box2
<div class="box1"></div> <div class="box2"></div>
-
设置宽高及背景颜色,对box2进行定位
div { width: 300px; height: 300px; } .box1 { background-color: red; } .box2 { background-color: blue; /* 定位box2,将box2与box1的四分之一进行层叠 */ position: absolute; top: 150px; left: 150px; }
-
效果:
静态定位:
介绍:
静态定位是默认值,就是之前认识的标准流。
代码:
position : static;
注意点:
- 静态定位就是之前的标准流,不能通过方位属性进行移动
- 之后说的定位不包括静态定位,一般特指后几种:相对,绝对,固定
相对定位:
介绍:
自恋型定位,相对于自己之前的位置进行移动
代码:
position : relative;
特点:
- 需要配合方位属性实现移动
- 相对于自己原来的位置进行移动
- 在页面中占位置------没有脱标
应用场景:
- 配合绝对定位组cp(子绝父相)
- 用于小范围移动
举例:
-
设置三个盒子box1,box2,box3
<div class="box1"></div> <div class="box2"></div> <div class="box3"></div>
-
设置宽高背景颜色,并将box2进行相对定位
div { width: 300px; height: 300px; } .box1 { background-color: red; } .box2 { background-color: green; /* 对box2相对原位置进行定位 */ position: relative; top: 100px; left: 100px; } .box3 { background-color: blue; }
-
效果
绝对定位:
介绍:
拼爹型定位,相对于非静态定位的父元素进行定位移动
代码:
position : absolute;
特点:
- 需要配合方位属性实现移动
- 默认相对于浏览器可视区域进行移动
- 在页面中不占位置------已经脱标
应用场景:
配合相对定位组cp(子绝父相)
举例:
- box2绝对定位:
div {
width: 300px;
height: 300px;
}
.box1 {
background-color: red;
}
.box2 {
background-color: green;
/* 对box2进行绝对定位 */
position: absolute;
top: 100px;
left: 100px;
}
.box3 {
background-color: blue;
}
- 效果:
绝对定位到底相对于谁进行偏移:
-
若祖先元素中没有定位------默认相对于浏览器进行移动
-
若祖先元素中有定位------相对于 最近的 有定位 的祖先元素进行移动
-
举例:
father为son的父元素,son为sun的父元素
<div class="father"> <div class="son"> <div class="sun"></div> </div> </div>
对father进行定位后,sun的绝对定位的偏移会相对于father偏移
.father { width: 600px; height: 600px; background-color: pink; /* 对father元素进行一个相对定位 */ position: relative; top: 0; left: 0; } .son { width: 400px; height: 400px; background-color: skyblue; } .sun { width: 200px; height: 200px; background-color: blue; /* sun元素绝对定位,相对于最近有定位的祖先元素进行偏移 */ position: absolute; right: 0; bottom: 0; }
-
效果:
子绝父相介绍:
场景:
让子元素相对父元素进行自由移动
含义:
子元素:绝对定位;父元素:相对定位
子绝父相的好处:
父元素是相对定位,则对网页布局影响最小
注意:
在使用子绝父相的时候,如果发现父元素已经有了绝对定位了,此时直接子绝即可。
固定定位:
介绍:
死心眼型定位,相对于浏览器进行定位移动
代码:
position : fixed;
特点:
- 需要配合方位属性实现移动
- 相对于浏览器可视区域进行移动
- 在页面中不占位置------已经脱标
应用场景:
让盒子固定在屏幕中的某个位置