1. 首页
  2. 软件开发
  3. 子绝父相的原理

子绝父相的原理

  • 发布于 2024-09-20
  • 0 次阅读

1.子绝父相的解释

子级是绝对定位,父级要用相对定位。

2.特点

  1. 子级绝对定位,不会占有位置,可以放到父盒子里面的任何一个地方,不会影响其他的兄弟盒子。

  2. 父盒子需要加定位限制子盒子在父盒子内显示。

  3. 父盒子布局时,需要占有位置,因此父亲只能是相对定位。这就是子绝父相的由来,所以相对定位经常用来作为绝对定位的父级。

3.举例说明

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>子绝父相</title>
  </head>
  <style>
    /* 子绝父相:
      子元素使用绝对定位,父元素使用相对定位.让子元素相对于父元素进行自由的移动位置
      好处:对网页布局影响比较小.
  */
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    .father {
      /* 1.若父元素设置为绝对定位的时候,会脱标,不占位置,底下的模块会自动上浮,页面紊乱 */
      /* position: absolute; */
      position: relative;
      /* 2.若父元素设置为相对定位,子元素会相对于父元素移动位置,对页面影响较小,推荐使用!!! */
      top: 50px;
      left: 50px;
      width: 300px;
      height: 300px;
      background-color: pink;
    }
    .son {
      position: absolute;
      top: 0px;
      left: 200px;
      width: 100px;
      height: 100px;
      background-color: aqua;
    }
    .son1 {
      position: absolute;
      top: 100px;
      left: 100px;
      width: 100px;
      height: 100px;
      background-color: yellow;
    }
  </style>
  <body>
    <div class="father">
      <div class="son"></div>
      <div class="son1"></div>
    </div>
  </body>
</html>

4.总结

因为父级需要占有位置,因此是相对定位,子盒子不需要占有位置,则是绝对定位,另外在实际网页布局设计时,如果你全部使用相对定位时,则会在页面中占位置(没有脱标),将其移动时,会使偏移量数值增大,可能会在布局四周留下大量空白,所以我们推荐使用子绝父相。

原文链接: https://blog.csdn.net/2302_78593467/article/details/135954834