border-box isn't working as expected

瘦欲@ 提交于 2020-01-04 13:05:35

问题


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>

回答1:


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>


来源:https://stackoverflow.com/questions/41604549/border-box-isnt-working-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!