文档流又称正常流,是默认情况下HTML元素排版布局过程中元素会自动按照自上而下或从左往右进行流式排放的一种顺序。而position样式属性是用于定义建立元素布局所用的定位类型,该属性有多个属性值,主要有四个:static、relative、fixed、absolute。
一、static
默认值。没有定位,元素出现在正常流中(忽略 top, bottom, left, right 或者 z-index 声明)。示例如下:
<div style="border: 1px solid red; width: 300px; height: 300px;">
<div class="a" style="background-color: black;"></div>
<div class="a" style="background-color: yellow; position: static;"></div>
<div class="a" style="background-color: green;"></div>
</div>
<style>
.a{
width: 100px;
height: 100px;
}
</style>
运行结果如下图:
二、relative
生成相对定位的标签。因此,“left:20” 会向标签的left位置添加 20 像素。示例如下:
<div style="border: 1px solid red; width: 300px; height: 300px;">
<div class="a" style="background-color: black;"></div>
<div class="a" style="background-color: yellow; position: relative; left: 20px;"></div>
<div class="a" style="background-color: green;"></div>
</div>
<style>
.a{
width: 100px;
height: 100px;
}
</style>
运行结果如下图:
三、fixed
生成绝对定位的标签,相对于浏览器窗口进行定位,此时元素不会随着滚动调的滑动而滑动。元素通过 “left”, “top”, “right” 以及 “bottom” 属性进行定位。示例如下:
<div style="border: 1px solid red; width: 300px; height: 300px;">
<div class="a" style="background-color: black;"></div>
<div class="a" style="background-color: yellow; position: fixed; bottom: 30px; right: 30px;"></div>
<div class="a" style="background-color: green;"></div>
</div>
<br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br />
<style>
.a{
width: 100px;
height: 100px;
}
</style>
运行结果如下图:
向下滑动页面后结果如下图:
四、absolute
生成绝对定位的标签,相对于标签本身第一个position为非 static父元素进行定位。标签通过 “left”, “top”, “right” 以及 “bottom” 样式属性进行定位。如果该标签所在的父标签均没有设置position为非 static,则相对于浏览器窗口进行定位,但是此时元素会随着滚动调的滑动而滑动。示例如下:
1、该标签所在的父标签均没有设置position样式属性值为非static:
<div style="border: 1px solid red; width: 300px; height: 300px;">
<div class="a" style="background-color: black;"></div>
<div class="a" style="background-color: yellow; position: absolute; bottom: 30px; right: 30px;"></div>
<div class="a" style="background-color: green;"></div>
</div>
<br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br />
<style>
.a{
width: 100px;
height: 100px;
}
</style>
运行结果如下图:
向下滑动页面后结果如下图:
2、该标签所在的父标签设置position样式属性值为relative:
<div style="border: 1px solid red; width: 300px; height: 300px; position: relative;">
<div class="a" style="background-color: black;"></div>
<div class="a" style="background-color: yellow; position: absolute; bottom: 30px; right: 30px;"></div>
<div class="a" style="background-color: green;"></div>
</div>
<br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br />
<style>
.a{
width: 100px;
height: 100px;
}
</style>
运行结果如下图: