htmlcssborder-boxbox-sizing

border-box isn't working as expected


I have two parent elements, and 3 children inside. (#grandParent>#parent>#children*3) grandParent has a set height and width, and parent has padding applied. All elements have box-sizing: border-box.

With border-box applied, the padding should make the children smaller, but instead, it pushed it down, and retains its size. Why doesn't the children become smaller when the padding is applied?

JSFiddle

* {
  box-sizing: border-box;
}
#grandParent {
  width: 34px;
  height: 34px;
}
#parent {
  padding: 30px 5px;
}
.children {
  background: black;
  height: 3px;
  width: 100%;
  margin-bottom: 6px;
}
#reference {
  background-color: orange;
  width: 34px;
  height: 34px;
}
<div id="grandParent">
  <div id="parent">
    <div class="children"></div>
    <div class="children"></div>
    <div class="children"></div>
  </div>
</div>

<div id="reference"></div>


Solution

  • Using box-sizing: border-box on an element means you include padding and border into the width calculation of that element.

    You only have padding applied on the parent and so it takes effect only there.

    The width or height of parent is auto (default as its not specified). So try setting a height for instance, or adding height: inherit - you can see that the padding for parent is reduced on inspecting the element.

    See demo below:

    * {
      box-sizing: border-box;
    }
    #grandParent {
      width: 34px;
      height: 34px;
    }
    #parent {
      padding: 30px 5px;
      height: inherit;
    
    }
    .children {
      background: black;
      height: 3px;
      width: 100%;
      margin-bottom: 6px;
    }
    #reference {
      background-color: orange;
      width: 34px;
      height: 34px;
    }
    <div id="grandParent">
      <div id="parent">
        <div class="children"></div>
        <div class="children"></div>
        <div class="children"></div>
      </div>
    </div>
    
    <div id="reference"></div>