一、盒子的定位方式
盒子定位的属性:position
值为:
static : 默认值,无特殊定位。
relative:相对定位。
absolute:绝对定位。
fixed:绝对定位,相对域浏览器窗口进行定位。
二、相对定位
这边举一个例:
最开始: 位移后:
代码:
<!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>盒子的相对定位</title>
<style>
#container1 {
width: 100px;
height: 100px;
background-color: lightblue;
}
#container2 {
width: 100px;
height: 100px;
background-color:skyblue ;
position: relative;
left: 50px;
top: 50px;
}
#container3 {
width: 100px;
height: 100px;
background-color:royalblue ;
}
#container4 {
width: 100px;
height: 100px;
background-color: blue;
position: relative;
left: 80px;
bottom: 110px;
}
</style>
</head>
<body>
<div id="container1">1</div>
<div id="container2">2</div>
<div id="container3">3</div>
<div id="container4">4</div>
</body>
</html>
1. 其中的盒子2相对于它原来的位置定位,也就是说向左向上位移50px就会回到原来的位置。
2. 上面的盒子位移后会被下面的盒子盖住(没有位移的会默认在最下面。
三、绝对定位
这边用上面原本的代码为例子进行位移后:
#container1 {
width: 100px;
height: 100px;
background-color: lightblue;
position: absolute;
left: 50px;
top: 50px;
}
使用了绝对定位移动了 1 盒子,就相当于 1 盒子不见了,其他盒子正常运行。
#container2 {
width: 100px;
height: 100px;
background-color:skyblue ;
position: absolute;
left: 50px;
top: 50px;
}
同理,2 盒子移动,那就只剩下 3 和 4 盒子。而且2盒子移动会盖住1盒子。
#container4 {
width: 100px;
height: 100px;
background-color: blue;
position: absolute;
left: 100px;
bottom: 50px;
}
这是位置是相对于整个窗口,距离左100px,距离下50px。
四、固定定位
也是用以下上面的原本代码进行修改
#container1 {
width: 100px;
height: 100px;
background-color: lightgray;
position: fixed;
left: 50px;
top: 50px;
}
在原本的代码下还添加了许多个盒子2来体现固定定位的作用。
使用 fixed 的元素,相对于窗口固定,也就是无论上下滑动,盒子1总是会固定在窗口的某个位置.
五、练习
代码:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>绝对定位</title>
<style>
#div1{
width: 50px;
height:50px;
background-color: red;
position: absolute;
left: 220px;
top: 200px;
}
#div2{
width: 30px;
height: 30px;
background-color: green;
position: absolute;
left: 230px;
top: 210px;
}
#div3{
width: 50px;
height: 50px;
background-color: white;
position: absolute;
left: 100px;
top: 100px;
}
#div4{
width: 50px;
height: 50px;
background-color: white;
position: absolute;
right: 100px;
top: 100px;
}
#div5{
width: 300px;
height: 50px;
background-color: purple;
text-align: center;
position: absolute;
left: 100px;
bottom: 150px;
}
article{
width: 500px;
height: 500px;
background-color: gray;
position: absolute;
left: 100px;
top: 100px;
}
</style>
</head>
<body>
<article>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
<div id="div5">绝对定位测试</div>
</article>
</body>
</html>