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

Expand parent div based on child size + margin

目前,我在 div1 中有 div2,并且两者的大小相同。 我想将 borders/margins 添加到 div2 但不减小 div2 的大小而是扩大 div1 的大小。

知道怎么做吗?

外容器不需要widthheight属性。如果是这种情况,如果子元素 (.div2) 具有 margin,则外部容器 (.div1) 将展开。请参阅代码示例以更好地理解:)

.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>