position样式属性
文档流又称正常流,是默认情况下HTML元素排版布局过程中元素会自动按照自上而下或从左往右进行流式排放的一种顺序。
position:用于定义建立元素布局所用的定位类型,该属性有多个值:
static:默认值。没有定位,元素出现在正常流中(忽略 top, bottom, left, right 或者 z-index 声明)。
relative 生成相对定位的标签,。因此,“left:20” 会向标签的left位置添加 20 像素。
absolute 生成绝对定位的标签,相对于标签本身第一个position为非 static父元素进行定位。标签通过 “left”, “top”, “right” 以及 “bottom” 样式属性进行定位。如果该标签所在的父标签均没有设置position为非 static,则相对于浏览器窗口进行定位,但是此时元素会随着滚动调的滑动而滑动。
fixed 生成绝对定位的标签,相对于浏览器窗口进行定位,此时元素不会随着滚动调的滑动而滑动。元素通过 “left”, “top”, “right” 以及 “bottom” 属性进行定位。
inherit 规定应该从父元素继承 position 属性的值。注:IE浏览器都不支持"inherit"属性值
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>浮动</title>
</head>
<body>
<div id="rq"><!--id不能用数字开头-->
<div id="first"></div>
<div id="second"></div>
<div id="third"></div>
</div>
<style>
#first,#second,#third{
width: 100px;
height: 100px;
}
#rq{
border: 5px solid yellow;
width: 300px;
height: 300px;
}
#first{
background-color: red;
}
/*#second{
position: fixed;
right: 20px;
bottom: 20px;
background-color: gold; 【1】
}*/
#second{
position: relative;/*相对于自己定位*/
left: 20px;
top: 20px;
background-color: gold;【2】
}
/* #second{
position: absolute;相对于父标签定位,父标签的定位为非static
left: 20px;
top: 20px;
background-color: gold;【3】
}*/
#third{
width: 150px;
background-color: aqua;
}
</style>
</body>
</html>
任何元素都可以定位,但absolute或fixed元素会生成一个块级框,不论该元素本身是不是块级框。relative元素会相对于它在正常流中的默认位置偏移。
上述【1】【2】【3】执行结果依次是:
【1】
【2】
【3】