Why does padding result in a child larger than parent

Advertisements

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?

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

Leave a ReplyCancel reply