position的absolute与fixed共同点与不同点

这个问题面试被问到过~~

position属性是对于元素位置设置的属性,一般来说fixed是相对于window窗口的不会随着页面的滚动而位置发生变化

absolute是相对于页面中的元素位置设置的,所以位置会随着页面的滚动而发生变化,不会固定不变。如果页面没有滚动条的时候,两者的效果是一样的。

fixed:固定定位

absolute:绝对定位

区别很简单:

1、没有滚动条的情况下没有差异

2、在有滚动条的情况下,fixed定位不会随滚动条移动而移动,而absolute则会随滚动条移动

可以这么理解,fixed:固定在当前window不动, absolute:会随参照对象元素的高度和宽度变化而变化

一般fixed用在遮盖层和固定在页面某个位置,如固定在顶端的菜单栏,又如弹出提示框居中显示

下面例子可是简单测试两者之间的区别,注意拖动滚动条看差异

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <style>
        body {
        height:1000px;/*让窗体出现滚动条*/
        }
        .fixed {
            position: fixed;
            left: 100px;
            right: 100px;
            top: 100px;
            bottom: 100px;
            width: auto;
            height: auto;
            border: 1px solid blue;
            
        }
        .absolute {
            position: absolute;
            left: 100px;
            right: 100px;
            top: 100px;
            bottom: 100px;
            width: auto;
            height: auto;
            border: 1px solid red;
        }
    </style>
</head>
<body>
    <div class="fixed">fixed定位</div>
    <div class="absolute">absolute定位</div>
</body>
</html>

效果如下:当滚动条下拉时,absolute层会上移,fixed层不动

 

 

 

A:共同点:

1.改变行内元素的呈现方式,display被置为block;

2.让元素脱离普通流,不占据空间;

3.默认会覆盖到非定位元素上

 

B不同点:

absolute的”根元素“是可以设置的,而fixed的”根元素“固定为浏览器窗口。

当你滚动网页,fixed元素与浏览器窗口之间的距离是不变的。  

 

典型应用案例:

加了遮罩的居中弹窗,假如有很多屏,就得使用fixed,不然向下滚动弹窗和遮罩不会跟着走。

<input type="button" value="请点我"/>
<div class="bg"></div>
<div class="center"></div>
*{margin: 0; padding: 0;}
body{height: 6000px;}
.bg{background: #000; opacity:0.5; filter:alpha(opacity=50); width: 100%; height: 100%; top:0; left:0; position: fixed;}
.center{width: 500px; height: 500px; background: #fff; position: fixed; top:50%; left:50%; margin-left:-250px; margin-top:-250px;}

http://www.makaidong.com/shuiqing/379_202873.html 

https://www.php.cn/css-tutorial-369982.html

https://blog.csdn.net/m0_37972548/article/details/78906468

https://www.cnblogs.com/yuer20180726/p/11141288.html

https://blog.csdn.net/m0_37972548/article/details/78906468#commentBox

https://www.cnblogs.com/yuer20180726/p/11141253.html

 

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值