子div的宽度大于父div

新手上路,请多包涵

我需要我的子 div 坚持父 div 的底部,因此 position: absolutebottom: 0px 。我还需要子宽度与父宽度相同,我认为 box-sizing: border-box 可以工作,但由于填充和边距,子宽度仍然向右突出。

我该如何解决?

 .parent {
  height: 500px;
  min-width: 500px;
  position: relative;
  background-color: red;
}

.child {
  padding: 10px 10px 10px 10px;
  margin: 10px 10px;
  background-color: grey;
  bottom: 0px;
  box-sizing: border-box;
  position: absolute;
  width: 100%;
}
 <div class="parent">
  <div class="child"></div>
</div>

在 JSFiddle 上查看

原文由 user3642365 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 574
2 个回答

使用 left:0 / right:0 而不是 width:100% 来避免溢出,因为实际上你的元素在 500pxx+ parent 的 margin 20 内占用元素。

作为旁注, box-sizing: border-box 工作完美,但 元素内部,因此填充包含在宽度中,但边距当然不包含:

border-box 告诉浏览器在您为宽度和高度指定的值中考虑任何 边框填充ref

 .parent {
  height: 500px;
  min-width: 500px;
  position: relative;
  background-color: red;
}

.child {
  padding: 10px 10px 10px 10px;
  margin: 10px 10px;
  background-color: grey;
  bottom: 0px;
  box-sizing: border-box;
  position: absolute;
  left: 0;
  right: 0;
}
 <div class="parent">
  <div class="child" ></div>
</div>

原文由 Temani Afif 发布,翻译遵循 CC BY-SA 3.0 许可协议

你的想法是正确的。 margin 属性借助 left、top、right 和 bottom 将元素从其原始位置移动。更重要的是,保证金不服从容器边界限制。

请检查以下代码。要将子容器包含在父容器中,如果您想保留边距 margin-left 和 margin-right 属性,则应减小子容器的总宽度。

CSS3 calc 在处理两个不同的单位时非常聪明。 calc(100% - 20px) 将为您提供正确的宽度,该宽度将包含父元素内的子元素。

 .parent {
  height: 500px;
  min-width: 500px;
  position: relative;
  background-color: red;
}

.child {
  padding: 10px 10px 10px 10px;
  margin: 10px 10px;
  background-color: grey;
  bottom: 0px;
  box-sizing: border-box;
  position: absolute;
  width: calc(100% - 20px); //Subtracting left and right margin from the total width to avoid overflowing the parent container
}
 <div class="parent">
    <div class="child">
    </div>
</div>

原文由 forethought 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题