Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent padding from causing element to overflow its parent

Here is my HTML structure:

.parent{
  background-color:#f7f7f7;
  width: 100px;
  height: 100px;
  border:2px solid;
}

.child{
  height: 100%;
  width: 100%;
  background-color:#cf5;
  padding: 15px;
}
<div class="parent">
  <div class="child">something</div>
</div>

As you see div.child goes out of div.parent. That's because of padding: 15px;. Well, how can I calculate this in CSS:

.child{
    height: (100% - the number of padding);
    width: (100% - the number of padding);
}

So this is expected result: (noted that there also should be padding: 15px)

enter image description here

like image 509
stack Avatar asked Aug 21 '16 23:08

stack


1 Answers

Just add box-sizing: border-box to the child element.

.parent {
  background-color: #f7f7f7;
  width: 100px;
  height: 100px;
  border: 2px solid;
}
.child {
  height: 100%;
  width: 100%;
  background-color: #cf5;
  padding: 15px;
  box-sizing: border-box; /* NEW */
}
<div class="parent">
  <div class="child">something</div>
</div>

The CSS box-sizing property has an initial value of content-box. This means the box model calculates total width by adding the content plus padding plus borders. The calculation is similar for height.

With border-box, the box model includes padding and borders in the width / height calculation.

(Note that margins are always outside the calculation; they will be appended whether in content-box or border-box.)


A second possibility (arguably less efficient than box-sizing) would be the CSS calc function:

.parent {
  background-color: #f7f7f7;
  width: 100px;
  height: 100px;
  border: 2px solid;
}
.child {
  height: calc(100% - 30px);  /* NEW */
  width: calc(100% - 30px);   /* NEW */
  background-color: #cf5;
  padding: 15px;
}
<div class="parent">
  <div class="child">something</div>
</div>
like image 162
Michael Benjamin Avatar answered Oct 23 '22 10:10

Michael Benjamin