首页 文章

子div的宽度大于父级

提问于
浏览
3

我需要我的孩子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>

View on JSFiddle

3 回答

  • 0

    使用 left:0 / right:0 而不是 width:100% 来避免由于边距导致的溢出,因为实际上您的元素在父元素内占据了500px 20px(左/右边距) .

    作为旁注, box-sizing: border-box 工作正常但 inside 元素因此填充包含在宽度中但边缘当然不是:

    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>
    
  • 4

    你认为是对的 . margin属性在left,top,right和bottom的帮助下移动元素 . 更重要的是,保证金不遵守集装箱边界限制 .

    请检查以下代码 . 要将子容器包含在父容器中,如果要保留margin margin-margin和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>
    
  • -1

    尝试将子类中的边距更改为margin:0这会将子div向左和向下移动,以便子项的左下角与父级的左下角对齐 .

相关问题