谈css布局之position

position这个属性定义建立元素布局所用的定位机制。
主要有以下几个值:


static

所有元素在默认的情况下position属性均为static,而我们在布局上经常会用到的相对定位和绝对定位常用的属性top、bottom、left、right在position为static的情况下无效。
其用法为:在改变了元素的position属性后可以将元素重置为static让其回归到页面默认的普通流中。

<div style="border: solid 1px #0e0; width:200px;">
        <div style="height: 100px; width: 100px; background-color: Red;">
        </div>
        <div style="height: 100px; width: 100px; background-color: Green;">
        </div>
        <div style="height: 100px; width: 100px; background-color: Red;">
        </div>
    </div>

relative

relative 表现的和 static 一样,除非你添加了一些额外的属性。
在一个相对定位(position属性的值为relative)的元素上设置 top 、 right 、 bottom 和 left 属性会使其偏离其正常位置。其他的元素的位置则不会受该元素的影响发生位置改变来弥补它偏离后剩下的空隙。

<div style="border: solid 1px #0e0; width:200px;">
        <div style="height: 100px; width: 100px; background-color: Red;">
        </div>
        <div style="height: 100px; width: 100px; background-color: Green; position:relative; top:20px; left:20px;">
        </div>
        <div style="height: 100px; width: 100px; background-color: Red;">
        </div>
    </div>

absolute

absolute 与 fixed 的表现类似,但是它不是相对于视窗而是相对于最近的“positioned”祖先元素。如果绝对定位(position属性的值为absolute)的元素没有“positioned”祖先元素,那么它是相对于文档的 body 元素,并且它会随着页面滚动而移动。
还是刚才的例子,让绿色div绝对定位,为了清晰显示,第二个红色div改为黄色。

<div style="border: solid 1px #0e0; width:200px; position:relative;">
        <div style="height: 100px; width: 100px; background-color: Red;">
        </div>
        <div style="height: 100px; width: 100px; background-color: Green; position:absolute; top:20px; left:20px;">
        </div>
        <div style="height: 100px; width: 100px; background-color: Yellow;">
        </div>
    </div>

fixed

一个固定定位(position属性的值为fixed)元素会相对于视窗来定位,即便页面滚动,它还是会停留在相同的位置。和 relative 一样, top 、 right 、 bottom 和 left 属性都可用。

<div style="border: solid 1px #0e0; width:200px;">
        <div style="height: 100px; width: 100px; background-color: Red;">
        </div>
        <div style="height: 100px; width: 100px; background-color: Green; position:fixed; bottom:20px; left:20px;">
        </div>
        <div style="height: 100px; width: 100px; background-color: Yellow;">
        </div>
    </div>

所以说不管是页面纵向滚动条在页面顶端还是底端,绿色div总是在视口左下角。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容