static,fixed,relative,absolute
下面将用例子解释这四者之间的不同。
static是默认地定位;
relative是相对自己原本static的位置进行偏移,偏移的大小有top/left/right/bottom以及margin/padding决定
absolute是在相对其祖辈的固定位置
fixed是相对整个浏览器窗口的固定定位
1.static
在static定位的情况下,top、left、bottom、right、z-index不产生作用。
首先,理解html和body两者之间的关系。
在显示的时候,html是整个浏览器屏幕的边界开始,body在html的内部,并且body的margin是8px。
下面用同一个例子来阐述这记者之间的不同关系:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css"/>
</head>
<body>
<div id="con1"></div>
<div id="con2"></div>
</body>
</html>
/*
* @Author: Lin
* @Date: 2017-07-26 08:58:40
* @Last Modified by: Lin
* @Last Modified time: 2017-07-26 09:19:08
*/
html {
border:3px solid yellow;
}
body {
border:3px solid blue;
}
#con1 {
width: 400px;
height: 300px;
border: 2px solid green;
position: static;
top: 14px;
left: 14px;
}
#con2 {
width: 200px;
height: 100px;
border: 2px solid red;
}
显示的结果为:
注:border另外占据空间,与width和height无关。
注:static定位是以body内部的左上角为原点的。
2.relative
relative是相对其本身static的定位进行一定的偏移,其位置的改变不会影响同一个页面的其他元素的布局。从body边界的内部开始。
#con1 {
width: 400px;
height: 300px;
border: 2px solid green;
position: relative;
top: 0px;
left: 0px;
}
#con1 {
width: 400px;
height: 300px;
border: 2px solid green;
position: relative;
top: 10px;
left: 10px;
}
3.absolute
absolute是相对于其祖先元素的定位而言的,并且该祖先元素必须是非static定位的,如果没有找到祖先类是非static定位的,则以html作为原点进行偏移。absolute位置的改变会影响同一页面其他元素的布局。从html边界的外部开始。
#con1 {
width: 400px;
height: 300px;
border: 2px solid green;
position: absolute;
top: 14px;
left: 14px;
}
4.fixed
是固定在整个浏览器窗口的某一个角落,比如固定在右下角,当浏览器窗口被缩放的时候,其位置不变。