
position: relative和position: absolute 都可以改变元素在文档中的位置。
设置position: relative 或 position: absolute都可以让元素激活left、top、right、bottom 和 z-index 属性(默认情况下,这些属性未激活,设置了也无效)。
网页虽然看起来是平面的二维结构,但它其实是有z轴的,z轴的大小由z-index 控制,默认情况下,所有元素都是在z-index: 0 这一层的,这就是文档流。设置position: relative 或 position: absolute会让元素浮起来,也就是z-index大于0,它会改变正常情况下的文档流。
不同的是position: relative 会保留自己在z-index:0 层的位置,虽然它的实际位置可能因为设置了left、top、right、bottom 值是相对于自己在z-index:0层的位置,虽然它的实际位置可能因为设置了left、top、right、bottom值而偏离原来在文档流中的位置,但对其他仍然在z-index:0层的元素位置不会造成影响。
而position: absolute会完全脱离文档流,不再在z-index:0层保留占位符,其left、top、right、bottom 值是相对于自己最近的一个位置设置了position: relative 或 position: absolute的祖先元素的,如果祖先元素都没有设置position: relative 或 position: absolute,那么就相对于body元素。
除了position: relative 和 position: absolute,float也能改变文档流,不同的是,float属性不会让元素“上浮”到另一个z-index层,它仍然让元素在z-index:0层排列,float不像position: relative 和 position: absolute那样,它不能通过left、top、right、bottom属性精确地控制元素的坐标,它只能通过float:left 和 float:right 来控制元素在同层里“左浮”和“右浮”。float会改变正常的文档流排列,影响到周围元素。
另一个有趣的现象是position: absolute 和 float会隐式地改变display类型,不论之前什么类型的元素(display:none除外),只要设置了position: absolute 或 float中任意一个,都会让元素以display:inline-block的方式显示:可以设置长宽,默认宽度并不占满父元素。就算我们显示地设置display:inline或者display:block,也仍然无效(float在IE6 下的双倍边距bug就是利用添加display:inline来解决的)。值得注意的是,position: relative却不改变display的类型。
转自:《Web前端开发修炼之道》
We use cookies to improve your experience on our site. By using our site, you consent to cookies.
Manage your cookie preferences below:
Essential cookies enable basic functions and are necessary for the proper function of the website.
These cookies are needed for adding comments on this website.
Statistics cookies collect information anonymously. This information helps us understand how visitors use our website.
Google Analytics is a powerful tool that tracks and analyzes website traffic for informed marketing decisions.
Service URL: policies.google.com
You can find more information in our Cookie Policy and Cookie Policy.