Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does padding result in a child larger than parent

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 class="Outside">
  <div class="Container">
    <div class="Item">
    </div>
    <div class="Item">
    </div>
  </div>
  <div class="Container2">
    <div class="Item">
    </div>
    <div class="Item">
    </div>
  </div>
</div>

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 class="Outside">
  <div class="Container">
    <div class="Item">
    </div>
    <div class="Item">
    </div>
  </div>
  <div class="Container2">
    <div class="Item">
    </div>
    <div class="Item">
    </div>
  </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading