今天跟随pink老师学习了定位有关课程。
定位包括
- 静态定位
- 相对定位
- 绝对定位
静态定位是元素的默认定位方式,无定位的意思。他相当于border: none;中的none,在不要定位的时候使用。
相对定位(relative):
相对定位是元素相对于它原来在标准流中的位置来说的。(自恋型)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>relative两个性质</title>
<style>
div {
width: 200px;
height: 200px;
background-color: pink;
}
.two {
background-color: purple;
}
</style>
</head>
<body>
<div>1</div>
<div class="two">2</div>
<div>3</div>
</body>
</html>
出现下面三个方框:
我们给方框2加个相对定位,再偏移下,效果会怎么样呢:
position: relative;
top: 100px;
left: 100px;
得到relative“相对定位”的两个结论。
- 相对于 自己原来在标准流中的位置移动。
- 原来在标准中的区域继续占有,后面的盒子仍然以标准流的方式对待它
- 是会浮动到其他盒子的上面。
绝对定位(absolute)
绝对定位是相对于他父级元素 来设置元素的位置 (拼爹型)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>绝对定位</title>
<style>
.father {
width: 200px;
height: 200px;
background-color: pink;
/*子元素 跟着 父盒子 一起移动*/
margin: 100px;
}
.son {
width: 100px;
height: 100px;
background-color: purple;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
给子元素son加个absolute
position: absolute;
top: 50px;
left: 50px;
性质1:子盒子绝对定位 是以父盒子为主的 若父盒子没有定位 则以浏览器默认显示位置移动
性质2:绝对定位以带有定位的父级元素来移动位置
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>绝对定位2</title>
<style>
.grandfather {
width: 500px;
height: 500px;
background-color: skyblue;
}
.father {
width: 200px;
height: 200px;
background-color: pink;
}
.son {
width: 100px;
height: 100px;
background-color: purple;
}
</style>
</head>
<body>
<div class="grandfather">
<div class="father">
<div class="son"></div>
</div>
</div>
</body>
</html>
先给父盒子移动下
margin: 100px;
子盒子随着父盒子移动
再给子元素加个定位:
position: absolute;
top: 50px;
left: 50px;
/*子盒子绝对定位 是以父盒子为主的 若父盒子没有定位 则以浏览器默认位置移动*/
接着给爷元素加个定位
position: absolute;
left: 100px;
/*son 盒子 绝对定位 会一层,一层的向上找,父元素有,以父元素为准,爷元素有,以爷元素为准*/
下个例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>absolute3</title>
<style>
.father {
width: 500px;
height: 500px;
background-color: pink;
}
.damao {
width: 200px;
height: 200px;
background-color: purple;
}
.ermao {
width: 250px;
height: 250px;
background-color: skyblue;
}
</style>
</head>
<body>
<div class="father">
<div class="damao"></div>
<div class="ermao"></div>
</div>
</body>
</html>
/*1,若在damao身上加个绝对定位,原来的位置不会保留*/
.damao {
width: 200px;
height: 200px;
background-color: purple;
position: absolute;
top: 0;
left: 0;
}
/*2,若父盒子有定位,damao 盒子定位 以 父盒子为主*/
.father {
width: 500px;
height: 500px;
background-color: pink;
position: absolute;
}
利用绝对定位,盒子居中对齐小练习
<!DOCTYPE html>
固定定位(fixed):
固定定位是绝对定位的一种特殊形式:认死理型
- 完全脱标--完全不占位置
- 只认浏览器的可视窗口--“浏览器可视窗口+边便宜属性”来设置元素的位置
1,跟父元素没有任何关系
2,不随滚动条滚动
就是给小猴子设置了固定定位:
position: fixed;
bottom: 0;
right: 0;