一、定位
1、position:fixed 固定定位
元素的位置相对于浏览器窗口是固定位置。即使窗口是滚动的它也不会移动:
特性
特性:
1.元素脱离正常文档流,不占位(也脱离文本流,全脱)
2.始终相对于浏览器窗口四个角为原点进行固定定位的
3.不会随页面的内容滚动而滚动
4.能使不能设置宽高的行级元素设置宽高
5.提升层级
6.如果没有定位偏移属性,对元素本身有影响;
应用场景:
相对于窗口定位的元素如弹窗、跟随滚动的导航、侧边栏
注意:子元素设置绝对定位,父元素可以设置相对定位、绝对定位、固定定位, 这三种情况,参照元素都是父元素
<!DOCTYPE html> <html lang="en"> <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>Document</title> <style> .wrap { width: 300px; height: 300px; background-color: pink; /* position: relative; */ /* position: absolute; */ position: fixed; } .box1 { width: 100px; height: 100px; background-color: tomato; position: absolute; top: 100px; right: 50px; } </style> </head> <body> <!-- 这三种情况,子元素设置绝对定位,参照元素都是父元素 1.子绝父相(一般都用这个) 子元素设置绝对定位,父元素设置相对定位 2.子绝父绝 子元素设置绝对定位,父元素设置绝对定位 3.子绝父固 子元素设置绝对定位,父元素设置固定定位 --> <div class="wrap"> <div class="box1">box1</div> </div> </body> </html>
应用场景:
相对于窗口定位的元素如弹窗、跟随滚动的导航、侧边栏
注意:子元素设置绝对定位,父元素可以设置相对定位、绝对定位、固定定位, 这三种情况,参照元素都是父元素
<!DOCTYPE html> <html lang="en"> <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>Document</title> <style> .wrap { width: 300px; height: 300px; background-color: pink; /* position: relative; */ /* position: absolute; */ position: fixed; } .box1 { width: 100px; height: 100px; background-color: tomato; position: absolute; top: 100px; right: 50px; } </style> </head> <body> <!-- 这三种情况,子元素设置绝对定位,参照元素都是父元素 1.子绝父相(一般都用这个) 子元素设置绝对定位,父元素设置相对定位 2.子绝父绝 子元素设置绝对定位,父元素设置绝对定位 3.子绝父固 子元素设置绝对定位,父元素设置固定定位 --> <div class="wrap"> <div class="box1">box1</div> </div> </body> </html>
2、position:static静态定位
表示“将元素放在文档布局流的默认位置,HTML 元素的默认值,即没有定位,遵循正常的文档流对象。
margin 负间距原理
使用margin属性的负间距实现具有width属性和height属性的绝对定位元素的居中
position: absolute;
left: 50%;
/* 定位元素盒的宽度的一半 */
top: 50%;
/* 定位元素盒的高度的一半 */
margin-left: -100px;
/* -定位元素本身的宽度的一半 */
margin-top: -100px;
/* -定位元素本身的高度一半 */
-
常用于重置 定位属性
-
静态定位的元素不会受到 top, bottom, left, right影响。
-
定位元素的层级顺序
-
层级
语法: z-index: n;标签添加定位之后,可以覆盖在页面的其他标签上
后面加载的定位元素默认会覆盖在先加载的定位元素上
z-index属性:设置定位元素的叠放次序
特性:
1.z-index的属性值越大,它的层级就越高
2.属性值可以取值为正数,0,负数,没有单位(整数)
3.属性值取值相同的情况下,按照结构中的顺序排列次序,后来居上
4.正值向上调整层级,负值向下调整层级
注意:z-index属性要与定位一起使用才有效,否则无效
div {
width: 100px;
height: 100px;
}.box1 {
background-color: red;
position: absolute;
top: 40px;
left: 40px;
z-index: 1;
}.box2 {
background-color: blue;
position: absolute;
top: 60px;
left: 60px;
z-index: 1;
}.box3 {
background-color: pink;
position: absolute;
top: 80px;
left: 80px;
z-index: 6;
}.box4 {
background-color: purple;
z-index: 100;
} -
实现盒子居中的方法
方法一:
-
实现思路:margin负值配合百分比