了解position
从字面上来看,position即“位置”的意思,position标签作用是建立元素布局。
在介绍position之前,先来了解一下文档流。
文档流又称正常流,是默认情况下HTML元素排版布局过程中元素会自动按照自上而下或从左往右进行流式排放的一种顺序。
而position作用就是让指定元素脱离文档流,且相对于它在文档流中默认位置偏移(或不动)。
position的属性值及应用
position有有如下几个属性:
值 | 描述 |
static |
默认值。没有定位,元素出现在正常流中(忽略 top, bottom, left, right 或者 z-index 声明)。 |
relative | 生成相对定位的标签,相对于原标签位置偏移或静止。 |
absolute | 生成绝对定位的标签,相对于标签本身第一个position为非 static父元素进行定位。标签通过 “left”, “top”, “right” 以及 “bottom” 样式属性进行定位。如果该标签所在的父标签均没有设置position为非 static,则相对于浏览器窗口进行定位,但是此时元素会随着滚动调的滑动而滑动。 |
fixed | 生成绝对定位的标签,相对于浏览器窗口进行定位,此时元素不会随着滚动调的滑动而滑动。元素通过 "left", "top", "right" 以及 "bottom" 属性进行定位。 |
relative属性示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div style="border: solid red 1px;">
<div style="background-color: yellowgreen; width: 100px; height: 100px;"></div>
<div style="position: relative; left: 20px; bottom: 20px; background-color: dodgerblue; width: 100px; height: 100px;"></div>
<div style="background-color: gold; width: 100px; height: 100px;"></div>
</div>
</body>
</html>
效果如下:
fixed属性示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div style="border: solid red 1px;">
<div style="background-color: yellowgreen; width: 100px; height: 100px;"></div>
<div style="position: fixed; right: 20px; bottom: 20px; background-color: dodgerblue; width: 100px; height: 100px;"></div>
<div style="background-color: gold; width: 100px; height: 100px;"></div>
</div>
</body>
</html>
效果如下图: