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
)
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With