同时使用position和padding(或者margin)时出现的问题和解决方法

  • Post author:
  • Post category:其他


因为position: absolute;会使元素脱标,脱标之后父盒子的padding或者子盒子的margin会失效,这时会出现一些问题:

 <style>
      * {
        box-sizing: border-box;
      }
      .fa {
        width: 400px;
        height: 300px;
        background-color: skyblue;
        margin: 200px auto;
        position: relative;
        /* 给父盒子设置内边距不会起效果 */
        padding: 0 20px;
      }
      .son {
        width: 100%;
        height: 100px;
        background-color: pink;
        /* 使用了定位 */
        position: absolute;
        left: 0;
      }
    </style>

  <body>
    <div class="fa">
      <div class="son"></div>
    </div>
  </body>

显示效果中父盒子的padding失效:

或者是这样:

<style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      .fa {
        width: 400px;
        height: 300px;
        background-color: skyblue;
        position: relative;
      }
      .son {
        width: 100%;
        height: 100px;
        background-color: pink;
        position: absolute;
        margin-left: 20px;
      }
    </style>
    <div class="fa">
      <div class="son"></div>
    </div>

显示效果子盒子的外边距还是有效的:

如果设置的不是margin-left而是margin-top,生效并且不会触发外边距塌陷



版权声明:本文为Rome_z原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。