代码之家  ›  专栏  ›  技术社区  ›  yoan26

根据子大小+边距展开父div

  •  1
  • yoan26  · 技术社区  · 8 年前

    我想在div2中添加边框/边距,但不是减小div2的大小,而是扩展div1的大小。

    enter image description here

    1 回复  |  直到 8 年前
        1
  •  3
  •   Gerrit    8 年前

    外部容器不需要 width height .div1 )如果子元素( .div2 )有 margin 。请参阅代码示例以更好地理解:)

    .div1 {
      border: 4px solid #111;
      width: auto; /* remove width */
      height: auto; /* remove height */
      display: inline-block;  /* make it more flexible */
    }
    
    .div2 {
      width: 100px;
      height: 100px;
      background: cyan;
    }
    
    .div2.with-margin {
      margin: 20px;
    }
    <div class="div1">
      <div class="div2"></div>
    </div>
    <div class="div1">
      <div class="div2 with-margin"></div>
    </div>