position
的作用就是将元素在网页中定位,position
的设定值分为这么几种:
static
absolute
relative
fixed
sticky
下面我们按照这几个设定值分别来说明
position: static;
HTML 里所有的元素的 position
默认值都是 static
。static
会跟随 HTML 排版的流程(flow)移动。
top
、bottom
、left
、right
等属性都不会生效。
position: absolute;
absolute
元素会固定在其所设定的位置,不会跟随 HTML 排版的流程移动。但其会跟随页面的滚动而移动。
如果 absolute
元素嵌套在一个 absolute
元素内,其 top
、bottom
、left
、right
将会根据父元素的位置来相对定位。
position: relative;
relative
和 static
很相似,都会跟随 HTML 排版的流程而移动。
而它比 static
多了 top
、bottom
、left
、right
的设定。
在 relative
元素里面的 absolute
元素会根据 relative
的位置去定位,而 static
则不会。
position: fixed;
fixed
会定位到屏幕中的固定位置,不会跟随页面的滚动而移动。
如果 fixed
元素没有设定 top
、bottom
、left
、right
属性的话,fixed
将会根据 relative
去定位。
可是如果 fixed
元素有设定 top
、bottom
、left
、right
属性的话,即使是放在 relative
元素里,fixed
也还是会根据页面,就是 body
去定位,也不会根据 relative
定位。
position: sticky;
sticky
元素会在滚动过程中,当贴到顶部的时候,固定在顶部,贴在顶部的原因是将其 top
属性设置为 0,所以当它的 top
与上方相距为 0 时将会触发。
目前还有一些主流的浏览器不支持 sticky
,IE 浏览器的所有版本均不支持。