css定位absolute relative fixed

    xiaoxiao2026-08-03  4

    一.absolute

    相对拥有absolute或者relative父级进行定位,也就是他会一直寻找自己父级是否有absolute或者relative属性,如果找到,选择最近的进行定位,如果找不到就相对BODY左上角进行定位。脱离文档流。一般用在父级拥有absolute或者relative属性,我们希望元素能够相对父级移动,设置脱离父级元素范围内。

    二.relative

    相对自身原来位置进行定位,不可层叠,不脱离文档流(也就是说它仍然处在父级div中,受父级属性影响,比如说padding)。相对自身位置就是说当你不给元素设置属性时,元素所在的位置,设置relative后就相对自身位置进行移动。

    三.fixed

    相对浏览器可视窗口进行定位,不受滚动影响。这个跟文档(也就是整个网页,从头到尾不同),如果是跟文档定位,当我们下滑滚动条时,元素就被滑到了上方去。而相对浏览器窗口定位,无论我们如何滑动html文档,浏览器的窗口是不会变的。

    四.static

    默认值,不做改变,无法使用z-index。

    五.z-index

    类似于将整个浏览器三维化,元素可以互相重叠,z-index越大显示越在前面,就行一本书一样。每一页就是一个元素。页数越在前面说明z-index越大。

    六.测试

    <html><head> <style type="text/css"> body{margin:0px;padding:0px;line-height:100%;} div { width:100px; height:100px; display:inline-block; border:1px solid #ffffff; text-align:center; } #main { width:400px; height:300px; border: 1px solid #000; background-color: #FF9800; } </style> </head> <body> <div id="main" style=" position: relative; margin: 50px; padding: 80px; "> 由于main div有padding,所以文字位置才是它的width;main背景色包含padding部分 <div style=" position: static; left: 83px; top: 0px; background-color: #4CAF50; ">static一般默认属性,设置top,left无效</div> <div style=" position: absolute; left: 600px; top: 260px; background-color: #E91E63; ">absolute脱离文档流,相对main定位</div> <div style=" position: relative; left: 0px; top: 0px; background-color: #2196F3; z-index:11 ">relative未脱离文档流,受main padding影响,相对本身原位置定位</div> <div style=" position: fixed; left: 10px; top: 10px; background-color: #FF5722; ">fixed脱离文档流,相对窗口定位</div> </div> </body></html>
    转载请注明原文地址: https://ju.6miu.com/read-1310811.html
    最新回复(0)