div不占位置_不是吧,不是还有人不知道绝对定位和相对定位的区别吧

相对定位和绝对定位区别

相对定位

position:relative

相对于原来的位置移动,元素不脱离文档流,不影响其他元素的布局
举个

.box {
      position: relative;
      top: 100px;
      left: 100px;
      width: 100px;
      height: 100px;
      background-color: red;
    }

e1e1c55c3819e60ce41553638ebc43bc.png


由图片可以见 box 定位后相对于原来的位置上偏移 100px ,左偏移 100px

绝对定位

position:absolute

元素会脱离文档流,如果设置偏移量,会影响其他元素的位置定位


1.相对于最近的非 static 祖先元素定位


举个

    body{
          position: relative;
          height: 100px;
        }

    .box {
      position: absolute;
      top: 100px;
      left: 100px;
      width: 100px;
      height: 100px;
      background-color: red;
    }

1bb0949512d0cf1535ce47c6bf95df81.png


由图片可以见 box 绝对定位后相对于相对定位的父元素body上偏移 100px ,左偏移 100px


2.在1说明的祖先元素不存在时,元素相对于 初始包含块 定位


举个

初始包含块: 包含根元素html的一个矩形。他的尺寸是视口 viewport (for continuous media) 或分页媒体 page media (for paged media)

343703e78e9abf2b34a830d1154de971.png


由图片可以见 box 绝对定位后相对于初始包含块下偏移 100px ,左偏移 100px
网上很多资料说当父级元素中不存在相对定位,那么它的参照物就是body或者html都是不对的,感兴趣的小伙伴可以试一试
速记图

6cdde10c92867501fa6f72d50f254b2c.png


源码

  • 相对定位
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <meta charset="UTF-8">
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .box {
      position: relative;
      top: 100px;
      left: 100px;
      width: 100px;
      height: 100px;
      background-color: red;
    }
  </style>
</head>
<body>
  <div class="box"></div>
</body>
</html>
  • 绝对定位1
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <meta charset="UTF-8">
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    body{
      position: relative;
      height: 100px;
    }

    .box {
      position: absolute;
      top: 100px;
      left: 100px;
      width: 100px;
      height: 100px;
      background-color: red;
    }
  </style>
</head>
<body>

<div class="box"></div>

</body>
</html>
  • 绝对定位2
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <meta charset="UTF-8">
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    body{
      height: 100px;
    }

    .box {
      position: absolute;
      bottom: 100px;
      left: 100px;
      width: 100px;
      height: 100px;
      background-color: red;
    }
  </style>
</head>
<body>

<div class="box"></div>

</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值