Home > Mobile >  Why does padding result in a child larger than parent
Why does padding result in a child larger than parent

Time:12-30

Why does the "Container" overflow its parent, while the "Container2" does not? The only difference is the padding inside the "Container". Why should this stretch its outer size?

.Outside {
  width: 400px;
  height: 1000px;
  padding: 0px;
  background-color: orange;
}

.Container {
  width: 100%;
  padding: 5px;
  display: flex;
  background-color: blue;
  flex-direction: column;
}

.Container2 {
  width: 100%;
  display: flex;
  background-color: blue;
  flex-direction: column;
}

.Item {
  background-color: red;
  width: 100%;
  height: 50px;
}
<div >
  <div >
    <div >
    </div>
    <div >
    </div>
  </div>
  <div >
    <div >
    </div>
    <div >
    </div>
  </div>
</div>

https://jsfiddle.net/bvq0mrj4/19/

What is the correct way to avoid this if the padding is required?

CodePudding user response:

The simplest solution is to use box-siding:border-box so that the padding won't affect the size of the box

Box-Sizing

* {
    box-sizing: border-box;
}
.Outside {
  width: 400px;
  height: 1000px;
  padding: 0px;
  background-color: orange;
}

.Container {
  width: 100%;
  padding: 5px;
  display: flex;
  background-color: blue;
  flex-direction: column;
}

.Container2 {
  width: 100%;
  display: flex;
  background-color: blue;
  flex-direction: column;
}

.Item {
  background-color: red;
  width: 100%;
  height: 50px;
}
<div >
  <div >
    <div >
    </div>
    <div >
    </div>
  </div>
  <div >
    <div >
    </div>
    <div >
    </div>
  </div>
</div>

  • Related