CSS定位
- position:static 静态定位 (默认情况下的定位,是没有效果的。)
- position:relative 相对定位(相对于原来的位置进行定位,占用原文档流的空间)
- position:absolute 绝对定位(相对于定位了的父级或者body进行定位,一般在父级使用relative进行定位,子级相对于父级进行绝对定位,不占用原文档流空间)
- position:fixed 相对于浏览器窗口定位
<style>
.d1{
background-color:black;
width: 70%;
height: 1000px;
}
.d2{
background-color: blue;
width: 20%;
height: 150px;
}
.d3{
background-color: red;
width: 20%;
height: 150px;
}
.d4{
background-color: yellow;
width: 20%;
height: 150px;
}
<style>
<body>
<div class="d1">
<div class="d2"></div>
<div class="d3"></div>
<div class="d4"></div>
</div>
</body>
原效果图
给d2加一个向右100px的相对定位,给d3加一个100px的绝对定位。效果如下:
形成这样效果的原因是相对定位会占用原本的文档流让那里不可以有其他元素去占用,而绝对定位会向浮动一样,空出原本的文档流,后面的元素就会顶上前面的位置。
给d3设一个向右100px的position:fixed;这会根据浏览器进行定位。效果如下:
d3会根据浏览器的上下移动跟着移动。