CSS相对绝对定位 总结

CSS相对绝对定位 总结相对定位 relative 绝对定位 absolute fixed 在文档流的 relative 未完全脱离文档流的 浮动脱离文档流的 absolute fixedfloat 究竟有没有脱离文档流 为什么文字会围绕在 float 元素周围 而块状元素依然会忽略 float 元素 只能说明 float 未完全脱离文档流 一 解释 1 position st

position:relative | absolute | fixed | static | inherit

什么是文档流?
将窗体自上而下分成一行行, 并在每行中按从左至右的顺序排放元素,即为文档流。(自上而下,自左向右)


一、解释

1、position: static

这个是元素的默认定位方式,元素出现在正常的文档流中,会占用页面空间。不能使用top,bottom,left,right和z-index。

2、position: relative

(1)相对于其父级元素所剩余的未被占用的空间进行定位(在父元素由多个相对定位的子元素时可以看出)
就是:以自己作为参照,进行定位(即position为static时的位置)

3、position:absolute

(1)以最近的且不是static定位的祖先元素作为参考进行定位,如果其所有的父级元素都是static定位,那么此元素最终则是以当前窗口作为参考进行定位(body)。可以使用top,bottom,left,right进行位置移动,亦可使用z-index在z轴上面进行移动。
(2)脱离文档流,不会占用页面空间。
(3)absolute使用margin时,不管它有没有已经定位的祖先元素,都会以它原来所在文档流中的位置作为参照。此时margin-top、margin-bottom不再对文档流中的元素产生影响,因为该元素已经脱离了文档流。对于relative、absolute、fixed定位元素,使用 left、right、top、bottom属性与margin属性混合使用会产生累加效果。

4、position: fixed

position: fixed直接以浏览器窗口作为参考进行定位。其它特性同absolute定位。


二、例子说事

例1、position: relative; left:0px(或right:0px)

<style> *{ 
       margin: 0;padding: 0;} #div{ 
        width: 300px; height: 300px; background:#ccc; position: relative;/*或者position: absolute;*/ left: 50%; margin-left: -150px; } #div span{ 
        background: orange; } #child{ 
        position: relative; top:0; left: 0;/*换为right: 0; 输出效果一样*/ background: green; width: 100px; height: 100px; } </style> <body> <div id="div"> <span>1dadada1</span> <div id=child></div> <a href="">asdasdasdadad</a> </div> </body> 

在这里插入图片描述

例2、position: relative; right:100px;
将例1代码修改为如下,其他不变。

#child{ 
       position: relative; top:0; right:100px; background: green; width: 100px; height: 100px; } 

在这里插入图片描述

例3、position:absolute; left:0px;
将例1代码修改为如下,其他不变。

#child{ 
        position: absolute; top:0; left: 0; background: green; width: 100px; height: 100px; } 

CSS相对绝对定位 总结

例4、position:absolute; right:0px;
将例1代码修改为如下,其他不变。

#child{ 
         position: absolute; top:0; right: 0; background: green; width: 100px; height: 100px; } 

在这里插入图片描述

例5、position:absolute; top:60px;margin-top: 70px;

将例1代码修改为如下,其他不变。

#child{ 
          position: absolute; top:60px; left: 0; margin-top: 70px; background: green; width: 100px; height: 100px; } 
#child{ 
          position: fixed; top:0; right: 0; background: green; width: 100px; height: 100px; } 

例7、position:fixed; top:10px;margin-top: 20px;
将例1代码修改为如下,其他不变。

#child{ 
          position: fixed; top:30px; left: 0; margin-top: 20px; background: green; width: 100px; height: 100px; } 

总结:

relative: 以自己作为参照,进行定位(即position为static时的位置)
absolute: 以最近的 且不是static定位的父级元素作为参照,进行定位的
fixed: 以浏览器窗口作为参考,进行定位的






版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/233391.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号